在传统的 Java 应用中,Bean 的生命周期很简单,使用关键字 new 实例化 Bean,当不需要该 Bean 时,由 Java 自动进行垃圾回收。

Spring 中 Bean 的生命周期较复杂,可以简单表示为:Bean 的定义 -> Bean 的初始化 -> Bean 的使用 -> Bean 的销毁。

Spring 根据 Bean 的作用域来选择管理方式。对于 singleton 作用域的 Bean,Spring 能够精确地知道该 Bean 何时被创建,何时初始化完成,以及何时被销毁;而对于 prototype 作用域的 Bean,Spring 只负责创建,当容器创建了 Bean 的实例后,Bean 的实例就交给客户端代码管理,Spring 容器将不再跟踪其生命周期。

了解 Spring 生命周期的意义就在于,可以利用 Bean 在其存活期间的指定时刻完成一些相关操作。一般情况下,会在 Bean 被初始化后和被销毁前执行一些相关操作。

Spring 官方提供三种方法实现初始化回调和销毁回调:

  1. 实现 InitializingBean 和 DisposableBean 接口;
  2. 在 XML 中配置 init-method 和 destory-method;
  3. 使用 @PostConstruct 和 @PreDestory 注解。

一、三种方式实现Bean初始化回调

1. 使用接口实现Bean初始化回调

 org.springframework.beans.factory.InitializingBean 接口提供了以下方法:

void afterPropertiesSet() throws Exception;

实现代码如下:

@Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("其次,调用InitializingBean的 afterPropertiesSet方法......");
    }

2. 配置XML实现Bean初始化回调

可以通过 init-method 属性指定 Bean 初始化后执行的方法。

<bean id="helloWorld" class="com.clzhang.spring.demo.HelloWorld" init-method="init2">
        <property name="message" value="Hello World!" />
    </bean>

同时加入实现代码:

public void init2() {
        System.out.println("最后,调用XML配置文件中指定的初始化方式......");
    }

3. 使用注解实现Bean初始化回调

使用 @PostConstruct 注解标明该方法为 Bean 初始化后的方法。

@PostConstruct
    public void init1() {
        System.out.println("最先调用@PostConstruct方式的初始化方法......" );
    }

二、@PostConstruct 注解的配置

1. 在配置文件中使用 context 命名空间之前,必须在 <beans> 元素中声明 context 命名空间

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

2. 然后才是引用

<context:annotation-config/>

3. 需要在项目中引用若干Spring包

  • spring-core-5.2.3.RELEASE.jar            包含Spring框架基本的核心工具类
  • spring-beans-5.2.3.RELEASE.jar         所有应用都要用到的Jar包,它包含访问配置文件、创建和管理Bean以及进行IoC或者DI操作相关的所有类
  • spring-context-5.2.3.RELEASE.jar       提供在基础IoC功能上的扩展服务
  • spring-expression-5.2.3.RELEASE.jar 定义Spring的表达式语言
  • spring-aop-5.2.3.RELEASE.jar            SpringAOP编程必备包
  • commons-logging-1.2.jar                     Spring依赖的第三方Jar包,记录日志用

 三、全部代码参考如下

1 .实体Bean 

package com.clzhang.spring.demo;

import org.springframework.beans.factory.InitializingBean;

import javax.annotation.PostConstruct;

public class HelloWorld implements InitializingBean {
    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public void getMessage() {
        System.out.println("message : " + message);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("其次,调用InitializingBean的 afterPropertiesSet方法......");
    }

    @PostConstruct
    public void init1() {
        System.out.println("最先调用@PostConstruct方式的初始化方法......" );
    }    

    public void init2() {
        System.out.println("最后,调用XML配置文件中指定的初始化方式......");
    }
}

2. 调用者

package com.clzhang.spring.demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

        HelloWorld objA = (HelloWorld) context.getBean("helloWorld");
        objA.setMessage("对象A");
        objA.getMessage();
        HelloWorld objB = (HelloWorld) context.getBean("helloWorld");
        objB.getMessage();
    }
}

3. Bean.xml配置

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

    <bean id="helloWorld" class="com.clzhang.spring.demo.HelloWorld" init-method="init2">
        <property name="message" value="Hello World!" />
    </bean>
    <context:annotation-config/>
</beans>

四、输出如下

dubbo scopemodel sprig 生命周期回调 spring生命周期回调_初始化

另:销毁回调同样有三种方式

1. 实现org.springframework.beans.factory.DisposableBean 接口的destroy()方法

2. 配置XML文件,设置destroy-method 属性指定 Bean 销毁后执行的方法

3. 使用 @PreDestory 注解标明该方法为 Bean 销毁前执行的方法

本文参考:

http://c.biancheng.net/spring/bean-life-cycle.html