Spring Ioc容器的目的是管理Bean。Bean 是存放在Spring Ioc容器中的,所以它也会在容器中存在生命周期,它的初始化,存活和销毁也需要一个过程。对于一些需要自定义生命周期的Bean,我们可以插入代码去改变它们的一些行为,以满足特定的需求,这就需要使用Spring Bean生命周期的知识了。
最好把生命周期记下来,面试可能会问
如果自定义Bean的生命周期,这个Bean类要实现 BeanNameAware, BeanFactoryAware,
ApplicationContextAware, InitializingBean接口,并重写对应方法。自定义初始化,销毁方法。
package com.yao.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.beans.BeansException; import org.springframework.beans.factory.*; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @Data @AllArgsConstructor @NoArgsConstructor public class User implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean { private String username; private String password; private Computer computer; public void init(){ System.out.println("【" + this.getClass().getSimpleName() +"】执行自定义初始化方法"); } public void destroy0(){ System.out.println("【" + this.getClass().getSimpleName() +"】执行自定义销毁方法"); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("【" + this.getClass().getSimpleName() +"】调用BeanFactoryAware接口的setBeanFactory方法"); } @Override public void setBeanName(String s) { System.out.println("【" + this.getClass().getSimpleName() +"】调用BeanNameAware接口的setBeanName方法"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("【" + this.getClass().getSimpleName() +"】调用InitializingBean接口的afterPropertiesSet方法"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("【" + this.getClass().getSimpleName() +"】调用ApplicationContextAware接口的setApplicationContext方法"); } }
通过一个bean包,实现BeanPostProcess,DisposableBean接口.并重写对应的postProcessBeforeInitialization postProcessAfterInitialization, destroy 方法这三个方法每个Bean都会调用.
public class BeanPostProcessImpl implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("【" + bean.getClass().getSimpleName() +"】对象"+ beanName + "开始实列化"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("【" + bean.getClass().getSimpleName() +"】对象"+ beanName + "实列化完成"); return bean; } }
public class DisposableBeanImpl implements DisposableBean { @Override public void destroy() throws Exception { System.out.println("【" + this.getClass().getSimpleName() +"】调用Disposable的destroy方法"); } }
使用自定义初始化,销毁方法时要在配置文件中声明 init-method destroy-method
证明生命周期效果图
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)