天天看点

Spring bean的声明周期

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 的使用,后面会详细这个后置处理器的原理