Spring生命周期不可不知的回调接口

上回说到 Spring bean生命周期中的InitializingBean接口,我们了解到这只是spring bean生命周期中修改bean的诸多方式之一,其实在整个生命周期中,修改bean的方式大致有如下几种:

  1. 实现 InitializingBean接口  afterPropertiesSet() 

  2. 实现 DisposableBean接口的 destroy()

  3. 给方法加@PostConstruct@PreDestroy注解,需要说明一点,这两个注解是JSR250标准中的,而SpringInitDestroyAnnotationBeanPostProcessor类实现了这个标准

  4. xml的方式定义bean时,指定init methoddestroy method

    <bean id="testBeanLifeCycle" class="org.springframework.samples.mvc.beanPostProcessor.TestBeanLiftCycle"
         
    init-method="xmlInit" destroy-method="xmlDestroy">
       <property
    name="message" value="Hello World!"/</bean>

在众多的lifecycle机制中,假设一个bean使用了上边所有的方式,那么它们的执行顺序是这样的:


  • Methods annotated with @PostConstruct

  • afterPropertiesSet() as defined by the InitializingBean callback interface

  • A custom configured init() method

  • Methods annotated with @PreDestroy

  • destroy() as defined by the DisposableBean callback interface

  • A custom configured destroy() method


我们在代码中来看

在Spring中,bean的生命周期管理都是由beanFactory来管理,上一篇我们有提到,实现了beanFactory的类AbstractAutowiredCapableBeanFactory完成了bean的init和destroy的工作,初始化方法是


invokeInitMethods方法如下


接下来看看destroy逻辑,在AbstractAutowiredCapableBeanFactory中我们找到destroy方法

再来看DisposableBeanAdapter的destroy做了什么



来看个小demo来验明正身

  • 定义Spring bean TestBeanLifeCycle

  • applicationContext.xml中声明bean

  • Junit方式启动容器

  • 然后我们会看到下面的输出:

说了这么多机制,那么我们在使用的时候要注意什么

推荐使用@PostConstruct@PreDestroy,因为这来自JSR250,Spring框架0耦合。

除此之外,Spring还提供了LifeCycle接口和LifeCycleProcessor接口,实现这些接口能让beanlifecycle关联到ContainerlifeCycle,当容器有启动,停止,刷新等动作时,会回调到bean

如果说所有这些Spring提供的机制还是不能满足你的需求,那么总有一款适合你——BeanPostProcessor接口,事实上在Spring架构内部,众多的beanPostProcessor实现,能完成各种接口的回调,或者自定义方法的触发。关于更多BeanPostProcessor,且听下回分解。





欢迎关注,期待与您的交流,让我们携手在通往牛逼的小路上徐徐前行。


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值