bean生命周期
bean的生命周期 建立----初始化------銷毀的過程
容器管理bean的生命周期 可以自定義初始化和銷毀方法
[email protected]
@Bean(initMethod = "init",destroyMethod = "destory")
//指定初始化 銷毀方法 這些方法必須無傳回值 可以抛異常
//單執行個體bean 容器關閉的時候銷毀 多執行個體bean 容器不會管理銷毀
public Person person(){
return new Person();
}
2.通過實作InitializingBean 定義初始化邏輯 DisposableBean 定義銷毀邏輯
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
public interface DisposableBean {
void destroy() throws Exception;
}
3.使用JSR250注解
@PostConstruct bean建立完成屬性指派完成後 執行初始化方法
@PreDestroy bean銷毀之前通知
4.BeanPostProcessor 後置處理器
public interface BeanPostProcessor {
//
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
總結 本篇介紹了四種定義bean生命周期的方法尤其為 BeanPostProcessor 的使用,後面會詳細這個後置處理器的原理