bean生命周期
bean的生命周期 创建----初始化------销毁的过程
容器管理bean的生命周期 可以自定义初始化和销毁方法
1.@Bean
@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 的使用,后面会详细这个后置处理器的原理
本文深入探讨了Spring框架中Bean的生命周期,包括创建、初始化和销毁阶段。详细解析了通过@Bean注解、实现InitializingBean和DisposableBean接口、使用JSR250注解以及BeanPostProcessor后置处理器来定制Bean生命周期的方法。
1万+

被折叠的 条评论
为什么被折叠?



