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

来源:互联网 发布:三维立体制作软件 编辑:程序博客网 时间:2024/06/06 12:41

上回说到 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,且听下回分解。





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


0 0
原创粉丝点击