1. IOC装配Bean的生命周期
了解Spring IoC初始化和销毁Bean的过程,这便是Bean的生命周期的过程。
它大致分为:
-
Bean定义
-
Bean的初始化
-
Bean的生存期
-
Bean的销毁4个部分。
2. Bean的定义
- Spring通过我们的配置,如@ComponentScan定义的扫描路径去找到带有@Component的类,这个过程就是一个资源定位的过程。
- 一旦找到了资源,那么它就开始解析,并且将定义的信息保存起来。注意,此时还没有初始化Bean,也就没有Bean的实例,它有的仅仅是Bean的定义。
- 然后就会把Bean定义发布到Spring IoC容器中。此时,IoC容器也只有Bean的定义,还是没有Bean的实例生成。
3. Bean的初始化
Spring在完成依赖注入之后,还提供了一系列的接口和配置来完成Bean初始化的过程
3.1 接口实现
package com.cb.c3.pojo;
@Component
public class BussinessPerson implements Person, BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean {
private Animal animal = null;
@Override
public void service() {
this.animal.use();
}
@Override
@Autowired
@Qualifier("dog")
public void setAnimal(Animal animal) {
System.out.println("延迟依赖注入");
this.animal = animal;
}
@Override
public void setBeanName(String beanName) {
System.out.println("【" + this.getClass().getSimpleName()
+ "】调用BeanNameAware的setBeanName");
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("【" + this.getClass().getSimpleName()
+ "】调用BeanFactoryAware的setBeanFactory");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("【" + this.getClass().getSimpleName()
+ "】调用ApplicationContextAware的setApplicationContext");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("【" + this.getClass().getSimpleName()
+ "】调用InitializingBean的afterPropertiesSet方法");
}
@PostConstruct
public void init() {
System.out.println("【" + this.getClass().getSimpleName()
+ "】注解@PostConstruct定义的自定义初始化方法");
}
@PreDestroy
public void destroy1() {
System.out.println("【" + this.getClass().getSimpleName()
+ "】注解@PreDestroy定义的自定义销毁方法");
}
@Override
public void destroy() throws Exception {
System.out.println("【" + this.getClass().getSimpleName()
+ "】 DisposableBean方法");
}
}
Bean后置处理器:
package com.cb.c3.life;
@Component
public class BeanPostProcessorExample implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor调用postProcessBeforeInitialization方法,参数【"
+ bean.getClass().getSimpleName()+ "】【" +beanName+"】 ");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor调用postProcessAfterInitialization方法,参数【"
+ bean.getClass().getSimpleName()+ "】【" +beanName+"】 ");
return bean;
}
}
3.2 第三方类接口实现
此时可以使用注解@Bean来配置自定义初始化和销毁方法
@Bean(initMethod ="init", destroyMethod = "destroy" )