文章目录
Bean的声明周期
因为bean的声明周期是:bean创建–初始化–销毁的方法
容器管理bean的声明周期:
-
我们可以自定义初始化和销毁方法,容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁的方法
-
构造(对象的创建)
-
单实例,在容器启动的时候创建对象
-
多实例,在每次获取的时候创建对象
-
-
BeanPostProcessor.postProcessBeforeInitialization 在初始化之前工作
初始化:对象创建完成,并赋值好,调用初始方法
BeanPostProcessor.postProcessAfterInitialization 在初始化之后工作 -
销毁:
- 单实例:容器关闭的时候销毁
- 多实例:容器不会管理这个bean:容器不会调用销毁方法
第一种:使用@bean指定初始化和销毁方法
指定初始化(init-method="")和销毁方法(destroy-method="")
@Bean(initMethod = "init",destroyMethod = "destroy")
public Boy boy(){
return new Boy();
}
public class Boy{
public void init(){
System.out.println("init()===");
}
public void destroy(){
System.out.println("destroy()===");
}
}
第二种:实现InitializingBean和DisposableBean接口
InitializingBean
:定义初始化逻辑
DisposableBean
:定义销毁逻辑
public class Car implements InitializingBean, DisposableBean {
public Car(){
System.out.println("car construtor");
}
@Override
public void destroy() throws Exception {
System.out.println("===destroy()===");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("===afterPropertiesSet()===");
}
}
输出结果
第三种:使用JSR250:@PostConstruct和 @PreDestroy
@PostConstruct
:在bean创建完成并且属性赋值完成后:来执行初始化方法
@PreDestroy
:在容器销毁bean之前通知我们进行清理工作
public class Boy {
public Boy() {
System.out.println("construct ... boy");
}
// 对象创建并赋值之后调用
@PostConstruct
public void postConstruct(){
System.out.println("初始化@PostConstruct");
}
// 对象移除对象之前调用
@PreDestroy
public void preDestroy(){
System.out.println("销毁@PreDestroy");
}
public void init(){
System.out.println("===init()===");
}
public void destroy(){
System.out.println("===destroy()===");
}
}
@Bean(initMethod = "init",destroyMethod = "destroy")
public Boy boy(){
return new Boy();
}
打印结果:
第四种:BeanPostProcessor-后置处理器
定义一个类实现BeanPostProcessor
public class Girl implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeforeInitialization==>"+beanName+"====>"+bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("AfterInitialization==>"+beanName+"====>"+bean);
return bean;
}
}
@Bean(initMethod = "init",destroyMethod = "destroy")
public Boy boy(){
return new Boy();
}
@Bean
public Girl girl(){
return new Girl();
}
输出结果:
由结果可知
-
postProcessBeforeInitialization()
方法在初始化之前调用 -
postProcessAfterInitialization()
在初始化之后调用