Spring 生命周期方法

理解Spring bean 的生命周期很容易。当一个 bean 被实例化时,它可能需要执行一些初始化使它转换成可用状态。同样,当 bean 不再需要,并且从容器中移除时,可能需要做一些清除工作。

Bean的完整生命周期经历了各种方法调用,这些方法可以划分为以下几类:

  • Bean自身的方法:这个包括了Bean本身被@PostConstruct和@PreDestroy注解的方法和通过配置文件中<bean>的init-method和destroy-method指定的方法
  • Bean生命周期回调接口方法:这个包括了BeanNameAware、BeanFactoryAware、ApplicationContextAware、InitializingBean和DiposableBean这些接口的方法
  • 容器级生命周期接口方法:这个包括了BeanPostProcessor 和BeanFactoryPostProcessor 这两个接口实现,一般称它们的实现类为“后处理器”。

本文后续讲解均基于 Spring Framework 4.3.3.RELEASE。

执行顺序

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

  1. 如果bean实现了 BeanNameAware接口,则调用BeanNameAware.setBeanName()
  2. 如果bean实现了BeanFactoryAware接口,则调用BeanFactoryAware.setBeanFactory()
  3. 如果bean实现了ApplicationContextAware接口,则调用ApplicationContextAware.setApplicationContext()
  4. @PostConstruct 注解指定的初始化方法
  5. 如果bean实现了InitializingBean接口,则调用InitializingBean.afterPropertiesSet()
  6. 调用<bean>的init-method属性指定的初始化方法
  7. @PreDestroy注解指定的销毁方法
  8. 如果bean实现了DiposibleBean接口,则调用DiposibleBean.destory()
  9. 调用<bean>的destroy-method属性指定的初始化方法

org.springframework.beans.factory.InitializingBean 接口

org.springframework.beans.factory.InitializingBean 接口指定一个单一的方法:

void afterPropertiesSet() throws Exception;

因此,你可以简单地实现上述接口和初始化工作可以在 afterPropertiesSet() 方法中执行,如下所示:

public class ExampleBean implements InitializingBean {
   public void afterPropertiesSet() throws Exception {
      // do some initialization work
   }
}

在基于 XML 的配置元数据的情况下,你可以使用 init-method 属性来指定带有 void 无参数方法的名称。例如:

<bean id="exampleBean" 
         class="examples.ExampleBean" init-method="init"/>

ExampleBean 类的定义:

public class ExampleBean {
   public void init() {
      // do some initialization work
   }
}

org.springframework.beans.factory.DisposableBean 接口

org.springframework.beans.factory.DisposableBean 接口指定一个单一的方法:

void destroy() throws Exception;

因此,你可以简单地实现上述接口并且结束工作可以在 destroy() 方法中执行,如下所示:

public class ExampleBean implements DisposableBean {
   public void destroy() throws Exception {
      // do some destruction work
   }

在基于 XML 的配置元数据的情况下,你可以使用 destroy-method 属性来指定带有 void 无参数方法的名称。例如:

<bean id="exampleBean"
         class="examples.ExampleBean" destroy-method="destroy"/>

ExampleBean 类的定义:

public class ExampleBean {
   public void destroy() {
      // do some destruction work
   }
}

示例

下面通过一个简单的Spring Bean来演示Bean的生命周期,验证一下上面所说的,代码如下:

package com.bytebeats.spring4.lifecycle;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2016-12-28 22:46
 */
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2016-12-28 22:44
 */
public class ExampleBean implements BeanFactoryAware, BeanNameAware, ApplicationContextAware,
        InitializingBean, DisposableBean {

    private BeanFactory beanFactory;
    private String beanName;
    private ApplicationContext applicationContext;

    public ExampleBean() {
        System.out.println("【构造器】调用ExampleBean的构造器实例化");
    }

    // 这是BeanFactoryAware接口方法
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out
                .println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
        this.beanFactory = beanFactory;
    }

    // 这是BeanNameAware接口方法
    @Override
    public void setBeanName(String beanName) {
        System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()");
        this.beanName = beanName;
    }

    // 这是ApplicationContextAware接口方法
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("【ApplicationContextAware接口】调用ApplicationContextAware.setApplicationContext()");
        this.applicationContext = applicationContext;
    }

    // 这是InitializingBean接口方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
    }

    // 这是DiposibleBean接口方法
    @Override
    public void destroy() throws Exception {
        System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
    }

    // 通过<bean>的init-method属性指定的初始化方法
    public void initMethod() {
        System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
    }

    // 通过<bean>的destroy-method属性指定的初始化方法
    public void destroyMethod() {
        System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
    }

    @PostConstruct
    public void init(){
        System.out.println("【@PostConstruct】注解方法init");
    }

    @PreDestroy
    public void preDestroy(){
        System.out.println("【@PreDestroy】注解方法preDestroy");
    }

}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="com.bytebeats.spring4.lifecycle"/>

    <bean id="exampleBean" class="com.bytebeats.spring4.lifecycle.ExampleBean" init-method="initMethod"
          destroy-method="destroyMethod" scope="singleton"/>

</beans>

测试类:

package com.bytebeats.spring4.lifecycle;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.concurrent.TimeUnit;

/**
 * ${DESCRIPTION}
 *
 * @author Ricky Fung
 * @create 2017-03-04 21:07
 */
public class LifecycleApp {

    public static void main(String[] args) throws InterruptedException {

        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

        ExampleBean exampleBean = (ExampleBean) context.getBean("exampleBean");
        System.out.println(exampleBean);

        //休眠3秒钟
        TimeUnit.SECONDS.sleep(3);

        context.close();
    }
}

运行结果:

【构造器】调用ExampleBean的构造器实例化
【BeanNameAware接口】调用BeanNameAware.setBeanName()
【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()
【ApplicationContextAware接口】调用ApplicationContextAware.setApplicationContext()
【@PostConstruct】注解方法init
【InitializingBean接口】调用InitializingBean.afterPropertiesSet()
【init-method】调用<bean>的init-method属性指定的初始化方法
com.bytebeats.spring4.lifecycle.ExampleBean@467f0da4
【@PreDestroy】注解方法preDestroy
【DiposibleBean接口】调用DiposibleBean.destory()
【destroy-method】调用<bean>的destroy-method属性指定的初始化方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容