对Spring Bean 生命周期方法的总结
@Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public BeanTest beanTest() {
return new BeanTest();
}
public class BeanTest implements InitializingBean, DisposableBean, BeanPostProcessor, ApplicationContextAware {
public BeanTest() {
System.out.println("1.constructor");
}
@PostConstruct
public void postConstruct() {
System.out.println("2.PostConstruct");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("3.InitializingBean:afterPropertiesSet");
}
public void initMethod() {
System.out.println("4.initMethod");
}
@PreDestroy
public void annDestroy() {
System.out.println("1.PreDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("2.DisposableBean:destroy");
}
public void destroyMethod() {
System.out.println("3.destroyMethod");
}
/*@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;
}*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
AnnotationConfigServletWebServerApplicationContext a = (AnnotationConfigServletWebServerApplicationContext) applicationContext;
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) a.getBeanFactory();
new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
beanFactory.removeBeanDefinition("beanTest");
}).start();
}
}
初始化:
- constructor
- PostConstruct
- InitializingBean:afterPropertiesSet
- initMethod
销毁:
- PreDestroy
- DisposableBean:destroy
- destroyMethod