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。
原因暂时未知,有知道的大神方便评论。