关注微信公众号【行走在代码行的寻路人】获取Java相关资料,分享项目经验及知识干货。
以下测试的源码地址:https://github.com/877148107/Spring-Annotation
-
Bean的生命周期
bean创建----初始化---销毁的过程
1.创建
bean对象创建,单实例:在容器启动的时候就创建对象;多实例:容器启动的时候不创建,每次获取的时候创建
2.初始化
对象创建完成并赋值后调用初始化方法
3.销毁
单实例:容器关闭后就销毁;多实例:容器关闭后不会销毁,容器不管理这个多实例bean
@Configuration
public class MyBeanLifeConfiguration {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car(){
return new Car();
}
}
public class Car {
public void car(){
System.out.println("car 创建");
}
public void init(){
System.out.println("car 初始化");
}
public void destroy(){
System.out.println("car 销毁");
}
}
-
Bean的初始化、销毁有四种方法进行
1.通过上面自定义初始化、销毁方法,并在注解当中去配置
2.通过实现初始化InitializingBean和销毁DisposableBean的接口
@Component
public class Cat implements InitializingBean, DisposableBean {
public void cat(){
System.out.println("cat 创建");
}
public void destroy() throws Exception {
System.out.println("Cat destroy。。。。。。。。。");
}
public void afterPropertiesSet() throws Exception {
System.out.println("Cat afterPropertiesSet。。。。。。。。。。");
}
}
3.可以使用JSR250;@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法,@PreDestroy:在容器销毁bean之前通知我们进行清理工作
4.通过实现接口【BeanPostProcessor】的方式
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
System.out.println("postProcessBeforeInitialization:"+o+"==>"+s);
return o;
}
public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
System.out.println("postProcessAfterInitialization:"+o+"==>"+s);
return o;
}
}
-
接口【BeanPostProcessor】的原理
Spring底层很多类实现了这个BeanPostProcessor后置处理器。很多注解功能都是通过这个接口实现的。
第一步:创建容器AnnotationConfigApplicationContext
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyBeanLifeConfiguration.class);
第二步:初始化自定义后置处理器创建并初始化MyBeanPostProcessor
当容器创建时回去扫描注解的组件bean添加到容器中,这里我们自己创建了一个自定义的后置处理器MyBeanPostProcessor