spring是一個ioc容器,容器初始化時,將初始化所有配置,或通過包掃描注入的bean。
某一個bean的生命週期:
- new這個bean
- 初始化這個bean依賴的bean2
- 將依賴的bean2注入到這個bean
- 如果這個bean實現了BeanNameAware接口,調用其實現方法setBeanName(配置的ID或註解傳入的ID)
- 如果這個bean實現了BeanFactoryAware接口,調用其實現方法setBeanFactory(可獲取到BeanFactory)
- 如果這個bean實現了ApplicationContextAware接口,調用其實現方法setApplicationContext(可獲取到applicationContext)
- 如果這個bean實現了BeanPostProcessor接口,調用其實現方法postProcessBeforeInitialization(可用於修改這個bean)
- 如果這個bean實現了InitializingBean接口,調用其實現方法afterPropertiesSet(bean的初始化方法)
- 如果這個bean是配置式,配置了init-method,則調用init-method指定的方法
- 如果這個bean實現了BeanPostProcessor接口,調用其實現方法postProcessAfterInitialization(可用於修改這個bean)
- 如果這個bean實現了DisposableBean接口,在這個bean銷燬時,調用其實現方法destroy
- 如果這個bean是配置式,配置的destroy-method,在這個bean銷燬時,則調用destroy-method指定的方法
測試驗證:
@Component("bt")
public class BeanTest implements BeanNameAware,ApplicationContextAware,BeanPostProcessor,InitializingBean,DisposableBean,BeanFactoryAware {
@Resource(name = "bt2")
private BeanTest2 bt2;
public BeanTest() {
super();
System.err.println("new了BeanTest");
}
public BeanTest2 getBt2() {
return bt2;
}
@Override
public void destroy() throws Exception {
System.err.println("銷燬");
}
@Override
public void afterPropertiesSet() throws Exception {
System.err.println("初始化");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.err.println("設置applicationContext上下文");
}
@Override
public void setBeanName(String name) {
System.err.println("設置bean名稱: " + name);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.err.println("初始化前");
System.err.println(bean + ":" + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.err.println("初始化後");
System.err.println(bean + ":" + beanName);
return bean;
}
@Override
public void setBeanFactory(BeanFactory arg0) throws BeansException {
System.err.println("設置beanFactory上下文");
}
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/applicationContext.xml");
applicationContext.registerShutdownHook();
//applicationContext.getBean("bt");
}
}
@Component("bt2")
public class BeanTest2{
public BeanTest2() {
super();
System.err.println("bt2初始化");
}
}
測試用的兩個類:BeanTest,BeanTest2
BeanTest2是BeanTest需要依賴注入的
用main方法測試的話
結果:
可看出執行順序大體是一致的,不過少了BeanPostProcessor的實現方法
如果直接開啓項目:
這個BeanPostProcessor的實現方法出現,不過並不是生效在當前的bean,而是生效在非當前bean的其他bean。
原因暫時未知,有知道的大神方便評論。