* bean的生命周期
* bean创建--初始化--销毁过程
* 我们可以自定义初始化和销毁方法:
对象创建:
单实例:容器启动的时候创建对象
多实例:每次获取的时候创建对象
初始化:对象创建完成,并赋值好,调用初始化方法
销毁:
单实例:容器关闭的时候销毁
多实例:容器不会管理这个bean,不会调用销毁方法
initMethod和destroyMethod
public class Car {
public Car(){
System.out.println("car constructor....");
}
public void init(){
Sys tem.out.println("car .... init....");
}
public void carDestroy(){
System.out.println("car ... destroy....");
}
}
@Bean(initMethod = "init", destroyMethod = "carDestroy")
public Car car(){
return new Car();
}
测试:
@Test
public void test01(){
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成");
//applicationContext.getBean(Car.class);
applicationContext.close();
}
InitializingBean和DisposableBean
InitializingBean:bean创建完成,属性赋值完成后
DisposableBean定义销毁逻辑
public class Car implements InitializingBean,DisposableBean {
public Car(){
System.out.println("car constructor....");
}
public void init(){
System.out.println("car .... init....");
}
public void carDestroy(){
System.out.println("car...carDestroy....");
}
@Override
public void destroy(){
System.out.println("car ... destroy....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("car...afterPropertiesSet.....");
}
}
@PostConstruct和@PreDestroy
JSR250
public class Car implements InitializingBean,DisposableBean {
public Car(){
System.out.println("car constructor....");
}
@PostConstruct
public void post(){
System.out.println("PostConstruct");
}
@PreDestroy
public void pre(){
System.out.println("PreDestroy");
}
public void init(){
System.out.println("car .... init....");
}
public void carDestroy(){
System.out.println("car...carDestroy....");
}
@Override
public void destroy(){
System.out.println("car ... destroy....");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("car...afterPropertiesSet.....");
}
}
BeanPostProcessor
BeanPostProcessor[interface]:bean的后置处理器
在bean初始化前后进行一些处理工作
postProcessBeforeInitialization:在bean创建之后,初始化方法之前
postProcessAfterInitialization:在bean创建之后,初始化方法之后
public class MyBeanPostProcessor implements BeanPostProcessor {
/**
* @param bean 创建的实例
* @param beanName bean的名字
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization......"+beanName+"...."+bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization......"+beanName+"...."+bean);
return bean;
}
}
执行结果:
源码:AbstractAutowireCapableBeanFactory