java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring中Bean的生命周期原理

Spring中Bean的生命周期原理解析:实例化、属性赋值、初始化、运行期和销毁

作者:中环留念

本文详细介绍了Spring IOC容器中Bean的生命周期管理,包括实例化、属性赋值、初始化方法、Bean运行期和销毁方法,通过示例展示了如何使用XML配置和注解方式来定义初始化和销毁方法,并解释了这些方法的特性和使用规则

1. 理解Bean的生命周期

在Spring IOC容器中,Bean的生命周期大致如下:

  1. 实例化:当启动Spring应用时,IOC容器就会为在配置文件中声明的每个<bean>创建一个实例。

  2. 属性赋值:实例化后,Spring就通过反射机制给Bean的属性赋值。

  3. 调用初始化方法:如果Bean配置了初始化方法,Spring就会调用它。初始化方法是在Bean创建并赋值之后调用,可以在这个方法里面写一些业务处理代码或者做一些初始化的工作。

  4. Bean运行期:此时,Bean已经准备好被程序使用了,它已经被初始化并赋值完成。

  5. 应用程序关闭:当关闭IOC容器时,Spring会处理配置了销毁方法的Bean

  6. 调用销毁方法:如果Bean配置了销毁方法,Spring会在所有Bean都已经使用完毕,且IOC容器关闭之前调用它,可以在销毁方法里面做一些资源释放的工作,比如关闭连接、清理缓存等。

这就是Spring IOC容器管理Bean的生命周期,帮助我们管理对象的创建和销毁,以及在适当的时机做适当的事情。

我们可以将生命周期的触发称为回调,因为生命周期的方法是我们自己定义的,但方法的调用是由框架内部帮我们完成的,所以可以称之为“回调”。

2. 理解init-method和destroy-method

让我们先了解一种最容易理解的生命周期阶段:初始化和销毁方法。这些方法可以在Bean的初始化和销毁阶段起作用,我们通过示例来演示这种方式。

为了方便演示XML和注解的方式,接下来我们会创建两个类来分别进行演示,分别为LionElephant,让我们一步一步对比观察。

2.1 从XML配置创建Bean看生命周期

先创建一个类Lion

package com.example.demo.bean;
​
public class Lion {
​
    private String name;
​
    public void setName(String name) {
        this.name = name;
    }
​
    public void init() {
        System.out.println(name + " has been initialized...");
    }
​
    public void destroy() {
        System.out.println(name + " has been destroyed...");
    }
}

XML中,我们使用<bean>标签来注册Lion

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
​
        <bean class="com.example.demo.bean.Lion"
              init-method="init" destroy-method="destroy">
            <property name="name" value="simba"/>
        </bean>
</beans>
​

加上主程序

package com.example.demo.application;
​
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ClassPathXmlApplicationContext;
​
@ComponentScan("com.example")public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}

运行结果:

在上述 XML 配置文件中,使用 <bean> 标签向 Spring IOC 容器中注册了一个 Lion 类型的 Bean。

  1. <bean> 标签的核心作用

<bean> 标签用于声明一个由 Spring 容器管理的对象,其中:

<bean> 标签中,定义了两个非常关键的属性:

init-method="init"
destroy-method="destroy"

这两个方法无需实现任何接口,只需在类中定义普通方法即可。

<property name="name" value="simba"/>

当 IOC 容器启动时,如果在 init() 方法中输出类似:

simba has been initialized...

说明 初始化方法已成功被 Spring 调用

当程序执行 context.close() 或应用正常关闭时,如果看到:

simba has been destroyed...

说明 销毁方法已成功被 Spring 调用

整个 Bean 生命周期可以总结为:

  1. IOC 容器启动

  2. Spring 根据 XML 配置创建 Bean 实例

  3. 完成属性注入(如 name = simba

  4. 调用 init-method 指定的初始化方法

  5. Bean 进入可使用状态

  6. IOC 容器关闭

  7. 调用 destroy-method 指定的销毁方法

  8. 所有 Bean 销毁完成,IOC 容器关闭

小结

在 IOC 容器初始化完成之前,Bean 默认已经被创建并完成了初始化操作; 当容器关闭时,Spring 会先销毁所有受其管理的 Bean,最后再销毁整个 IOC 容器。

通过这个简单的 XML 示例,可以直观地看到 Spring Bean 的创建、初始化和销毁全过程。 在实际开发中,我们可以根据需要,在这些生命周期回调方法中完成诸如资源初始化、连接建立、资源释放等操作

2.2 从配置类注解配置创建Bean看生命周期

这里再创建一个类Elephant和上面对比

package com.example.demo.bean;
​
public class Elephant {
   
​
    private String name;
​
    public void setName(String name) {
   
        this.name = name;
    }
​
    public void init() {
   
        System.out.println(name + " has been initialized...");
    }
​
    public void destroy() {
   
        System.out.println(name + " has been destroyed...");
    }
}

对于注解,@Bean注解中也有类似的属性:initMethoddestroyMethod,这两个属性的作用与XML配置中的相同。

package com.example.demo.configuration;
​
import com.example.demo.bean.Elephant;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
​
@Configuration
@ImportResource("classpath:applicationContext.xml")
public class AnimalConfig {
   
​
    @Bean(initMethod = "init", destroyMethod = "destroy")
    public Elephant elephant() {
   
        Elephant elephant = new Elephant();
        elephant.setName("Dumbo");
        return elephant;
    }
}

这里用@ImportResource("classpath:applicationContext.xml")引入xml配置创建Bean进行对比。

主程序改为如下:

package com.example.demo.application;
​
import com.example.demo.configuration.AnimalConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
​
@ComponentScan("com.example")public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}

运行结果:

注意:在Spring中,如果在Java配置中定义了一个Bean,并在XML中定义了一个相同idnameBean,那么最后注册的那个Bean会覆盖之前注册的,这取决于配置文件加载顺序,无论在Java配置中还是XML配置中定义的initMethoddestroyMethod,最后生效的总是后加载的配置中定义的。

init-method”是指定初始化回调方法的属性的统称,无论它是在XML配置还是Java配置中使用。同样地,“destroy-method”是指定销毁回调方法的属性的统称。后文我们讲解多种声明的周期共存的时候,将延续这种说法。

2.3 初始化方法与销毁方法的特性说明

在 Spring 框架中,为 Bean 配置初始化方法和销毁方法时,需要遵循一定的规范,否则 Spring 可能无法按预期触发生命周期回调。下面从几个常见特性出发,对这些方法的使用规则进行说明,并配合示例进行解释。

  1. 方法的访问权限不受限制

初始化方法和销毁方法在访问权限上没有强制要求,无论是 publicprotectedprivate,还是默认(包私有)权限,Spring 都可以正常调用。

这是因为 Spring 底层是通过反射机制来执行这些方法的,因此不会受到 Java 访问控制符的限制。

示例:

public class MyBean {
private void init() {// 初始化代码
    }
}

在上述示例中,即使 init() 方法被定义为 private,Spring 依然能够在 Bean 初始化阶段正确调用该方法。

在默认情况下,Spring 并不知道应该向初始化或销毁方法传递哪些参数,因此这些方法通常不应定义参数

示例:

public class MyBean {
public void init() {// 初始化代码
    }
}

需要注意的是,Spring 并非完全禁止带参数的方法。如果方法定义了参数,Spring 容器会尝试利用自动装配机制,按照类型或名称为参数匹配对应的 Bean 并进行注入。

但如果:

那么 Spring 会在应用启动阶段抛出异常,导致容器初始化失败。因此在实际开发中,一般不推荐在初始化或销毁方法中使用参数。

初始化方法和销毁方法的返回值对 Spring 容器来说没有任何实际意义,因此这些方法通常应定义为 void 类型。

示例:

public class MyBean {
public void init() {// 初始化代码
    }
}

即使将方法声明为带返回值的形式,例如:

public String init() {return "success";
}

Spring 也会直接忽略该返回值,不会对其进行任何处理。

在初始化或销毁过程中,如果发生错误,这些方法是允许抛出异常的,用于向 Spring 容器明确地反馈失败信息。

示例:

public class MyBean {
public void init() throws Exception {// 初始化代码
        if (somethingGoesWrong) {throw new Exception("Initialization failed.");
        }
    }
}

当初始化或销毁方法抛出异常(无论是检查型异常还是运行时异常)时,Spring 容器都会捕获该异常,并将其封装为 BeanCreationExceptionBeanDestructionException 后再次抛出,从而导致 Bean 的创建或销毁过程失败。

初始化方法和销毁方法本质上是作用于 Bean 实例生命周期的,而静态方法属于类级别,不依赖于具体实例,因此并不适合作为生命周期回调方法。

示例:

public class MyBean {
public static void init() {// 初始化代码
    }
}

如果将初始化或销毁方法定义为 static,Spring 并不会立即报错,但这种做法违背了生命周期方法应当绑定到 Bean 实例的设计原则,也不符合实际使用场景。

2.4 探究Bean的初始化流程顺序

  在上面的代码中,我们可以看出BeanIOC容器初始化阶段就已经创建并初始化了,那么每个Bean的初始化动作又是如何进行的呢?我们修改一下Lion,在构造方法和setName方法中加入控制台打印,这样在调用这些方法时,会在控制台上得到反馈。

package com.example.demo.bean;
​
public class Lion {
   
​
    private String name;
​
    public Lion() {
   
        System.out.println("Lion's constructor is called...");
    }
​
    public void setName(String name) {
   
        System.out.println("setName method is called...");
        this.name = name;
    }
​
    public void init() {
   
        System.out.println(name + " has been initialized...");
    }
​
    public void destroy() {
   
        System.out.println(name + " has been destroyed...");
    }
}

我们重新运行主程序:

@ComponentScan("com.example")public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}

运行结果

3. @PostConstruct和@PreDestroy

JSR250规范中,有两个与Bean生命周期相关的注解,即@PostConstruct@PreDestroy。这两个注解对应了Bean的初始化和销毁阶段。

@PostConstruct注解标记的方法会在bean属性设置完毕后(即完成依赖注入),但在bean对外暴露(即可以被其他bean引用)之前被调用,这个时机通常用于完成一些初始化工作。

@PreDestroy注解标记的方法会在Spring容器销毁bean之前调用,这通常用于释放资源。

3.1 示例:@PostConstruct和@PreDestroy的使用

我们这里还是用Lion类来创建这个例子,将Lion类修改为使用@PostConstruct@PreDestroy注解

package com.example.demo.bean;
​
import org.springframework.stereotype.Component;
​
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
​
@Componentpublic class Lion {
   
​
    private String name;
​
    public void setName(String name) {
   
        this.name = name;
    }
​
    @PostConstructpublic void init() {
   
        System.out.println("Lion is going through init.");
    }
​
    @PreDestroypublic void destroy() {
   
        System.out.println("Lion is going through destroy.");
    }
​
    @Overridepublic String toString() {
   
        return "Lion{" + "name=" + name + '}';
    }
}

Lion类加上@Component注解,让IOC容器去管理这个类,我们这里就不把Elephant类加进来增加理解难度了。

@PostConstruct@PreDestroy 注解标注的方法与 init-method / destroy-method 方法的初始化和销毁的要求是一样的,访问修饰符没有限制,private也可以。

我们可以注释掉之前的配置类和XML配置,因为和这里的例子没有关系,我们来看看主程序:

package com.example.demo.application;
​
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.example.demo.bean");
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}

运行结果

这里可以看到@PostConstruct@PreDestroy注解正确地应用在了Lion的初始化和销毁过程中。

注意:   @PostConstruct@PreDestroy可用于任何Java类,初始化和销毁方法与init-methoddestroy-method类似,但也有一定的区别。

  1. 这些方法必须是非静态的,否则Spring容器在启动或销毁时会抛出BeanCreationExceptionBeanDestructionException异常,导致创建或销毁bean失败。

  2. 这些方法推荐无参数,与init-methoddestroy-method的行为类似。

  3. 这些方法推荐无返回值,与init-methoddestroy-method的行为类似。

  4. 可以是任何访问级别,与init-methoddestroy-method的行为类似。

  5. 可以抛出异常,与init-methoddestroy-method的行为类似。

  6. 不能被final修饰,如果使用final修饰这两个注解的方法,在编译时不会报错,可以正常编译。但是在运行时,Spring容器在解析和设置注解时,会尝试使用CGLIBJDK动态代理生成子类,由于方法被final修饰,子类无法覆盖该方法,所以Spring容器会抛出异常,表示无法为生命周期方法生成代理,这会导致标注了final的生命周期方法无法被Spring调用。

  注意:init-methoddestroy-method方法被final修饰也无影响,因为Spring通过反射机制来调用init-methoddestroy-method,不需要生成代理子类,并没有试图覆盖这些方法。不过生命周期方法都不被建议设计为final的,这需要注意。

3.2 初始化和销毁——注解和init-method共存对比

@PostConstruct@PreDestroy注解与init-method/destroy-method属性如何共存呢?我们来看看

我们只用Lion类来举例子,在Lion类中添加新的open()close()方法

需要的全部代码如下:

Lion.java

package com.example.demo.bean;
​
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
​
​
public class Lion {
   
​
    private String name;
​
    public Lion() {
   
        System.out.println("Lion构造器");
    }
​
    public void setName(String name) {
   
        System.out.println("Lion设置name");
        this.name = name;
    }
​
    public void open() {
   
        System.out.println("配置类initMethod - 打开Lion。。。");
    }
​
    public void close() {
   
        System.out.println("配置类destroyMethod - 关闭Lion。。。");
    }
​
    @PostConstruct
    public void init() {
   
        System.out.println("@PostConstruct - Lion正在进行初始化。。。");
    }
​
    @PreDestroy
    public void destroy() {
   
        System.out.println("@PreDestroy - Lion正在进行销毁。。。");
    }
​
    @Override
    public String toString() {
   
        return "Lion{" + "name=" + name + '}';
    }
}

配置类AnimalConfig.java

package com.example.demo.configuration;
​
import com.example.demo.bean.Lion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
​
@Configuration
public class AnimalConfig {
   
​
    @Bean(initMethod = "open", destroyMethod = "close")
    public Lion lion() {
   
        return new Lion();
    }
}

主程序

package com.example.demo.application;
​
import com.example.demo.configuration.AnimalConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}

运行结果

这里可以看到@PostConstruct@PreDestroy注解的优先级始终高于配置类中@Bean注解的initMethoddestroyMethod属性。

4. 实现InitializingBean和DisposableBean接口

  这两个接口是 Spring 预定义的两个关于生命周期的接口。他们被触发的时机与上文中的 init-method / destroy-method 以及 JSR250 规范的注解相同,都是在 Bean 的初始化和销毁阶段回调的。下面演示如何使用这两个接口。

4.1 示例:实现InitializingBean和DisposableBean接口

创建Bean,我们让Lion类实现这两个接口:

Lion.java

package com.example.demo.bean;
​
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
​
​
@Component
public class Lion implements InitializingBean, DisposableBean {
   
​
    private Integer energy;
​
    @Override
    public void afterPropertiesSet() throws Exception {
   
        System.out.println("狮子已经充满能量。。。");
        this.energy = 100;
    }
​
    @Override
    public void destroy() throws Exception {
   
        System.out.println("狮子已经消耗完所有能量。。。");
        this.energy = 0;
    }
​
    @Override
    public String toString() {
   
        return "Lion{" + "energy=" + energy + '}';
    }
}

  InitializingBean接口只有一个方法:afterPropertiesSet()。在Spring框架中,当一个bean的所有属性都已经被设置完毕后,这个方法就会被调用。也就是说,这个bean一旦被初始化,Spring就会调用这个方法。我们可以在bean的所有属性被设置后,进行一些自定义的初始化工作。

  DisposableBean接口也只有一个方法:destroy()。当Spring容器关闭并销毁bean时,这个方法就会被调用。我们可以在bean被销毁前,进行一些清理工作。

主程序:

package com.example.demo.application;
​
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context
                = new AnnotationConfigApplicationContext("com.example.demo.bean");
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}
​

运行结果:

4.2 三种生命周期并存

Spring框架中,控制Bean生命周期的三种方式是:

  1. 使用Springinit-methoddestroy-method(在XML配置或者Java配置中自定义的初始化和销毁方法);

  2. 使用JSR-250规范的@PostConstruct@PreDestroy注解;

  3. 实现SpringInitializingBeanDisposableBean接口。

  接下来我们测试一下,一个Bean同时定义init-methoddestroy-method方法,使用@PostConstruct@PreDestroy注解,以及实现InitializingBeanDisposableBean接口,执行顺序是怎样的。

我们创建一个新的类Lion2,并同时进行三种方式的生命周期控制:

需要运行的全部代码如下:

package com.example.demo.bean;
​
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
​
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
​
@Component
public class Lion2 implements InitializingBean, DisposableBean {
   
​
    private Integer energy;
​
    public void open() {
   
        System.out.println("init-method - 狮子开始行动。。。");
    }
​
    public void close() {
   
        System.out.println("destroy-method - 狮子结束行动。。。");
    }
​
    @PostConstruct
    public void gainEnergy() {
   
        System.out.println("@PostConstruct - 狮子已经充满能量。。。");
        this.energy = 100;
    }
​
    @PreDestroy
    public void loseEnergy() {
   
        System.out.println("@PreDestroy - 狮子已经消耗完所有能量。。。");
        this.energy = 0;
    }
​
    @Override
    public void afterPropertiesSet() throws Exception {
   
        System.out.println("InitializingBean - 狮子准备行动。。。");
    }
​
    @Override
    public void destroy() throws Exception {
   
        System.out.println("DisposableBean - 狮子行动结束。。。");
    }
}
​

接着,我们注册Lion2

package com.example.demo.configuration;
​
import com.example.demo.bean.Lion2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
​
@Configuration
public class AnimalConfig {
   
​
    @Bean(initMethod = "open", destroyMethod = "close")
    public Lion2 lion2() {
   
        return new Lion2();
    }
}

然后让注解 IOC 容器驱动这个配置类,主程序如下:

package com.example.demo.application;
​
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context
                = new AnnotationConfigApplicationContext("com.example.demo");
        System.out.println("Spring容器初始化完成。");
        System.out.println("==================");
        System.out.println("Spring容器准备关闭");
        context.close();
        System.out.println("Spring容器已关闭。");
    }
}

运行结果:

从上面的结果,我们可以得出以下结论,在Spring框架中单实例Bean的初始化和销毁过程有这样的执行顺序:

初始化顺序:@PostConstruct → InitializingBean → init-method

销毁顺序:@PreDestroy → DisposableBean → destroy-method

在初始化Bean时,@PostConstruct注解方法会首先被执行,然后是实现InitializingBean接口的afterPropertiesSet方法,最后是init-method指定的方法。

在销毁Bean时,@PreDestroy注解方法会首先被执行,然后是实现DisposableBean接口的destroy方法,最后是destroy-method指定的方法

结合前面说过的属性赋值(构造器方法和setter方法),简单总结一下Spring Bean生命周期的流程:

  1. 实例化(通过构造器方法);

  2. 设置Bean的属性(通过setter方法);

  3. 调用Bean的初始化方法(@PostConstructafterPropertiesSet方法或者init-method指定的方法);

  4. Bean可以被应用程序使用;

  5. 当容器关闭时,调用Bean的销毁方法(@PreDestroydestroy方法或者destroy-method指定的方法)。

5. 原型Bean的生命周期

  原型Bean的创建和初始化过程与单例Bean类似,但由于原型Bean的性质,其生命周期与IOC容器的生命周期并不相同。

这里展示一下需要的全部代码。

Lion2.java

package com.example.demo.bean;
​
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
​
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
​
public class Lion2 implements InitializingBean, DisposableBean {
   
​
    private Integer energy;
​
    public void roar() {
   
        System.out.println("The lion is roaring...");
    }
​
    public void rest() {
   
        System.out.println("The lion is resting...");
    }
​
    @PostConstruct
    public void gainEnergy() {
   
        System.out.println("@PostConstruct - 狮子已经充满能量。。。");
        this.energy = 100;
    }
​
    @PreDestroy
    public void loseEnergy() {
   
        System.out.println("@PreDestroy - 狮子已经消耗完所有能量。。。");
        this.energy = 0;
    }
​
    @Override
    public void afterPropertiesSet() throws Exception {
   
        System.out.println("InitializingBean - 狮子准备行动。。。");
    }
​
    @Override
    public void destroy() throws Exception {
   
        System.out.println("DisposableBean - 狮子行动结束。。。");
    }
}

然后在SpringJava配置中声明并设定其为原型Bean

package com.example.demo.configuration;
​
import com.example.demo.bean.Lion2;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
​
@Configuration
public class PrototypeLifecycleConfiguration {
   
​
    @Bean(initMethod = "roar", destroyMethod = "rest")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public Lion2 lion() {
   
        return new Lion2();
    }
}
​

  如果我们只是启动了IOC容器,但并未请求Lion2的实例,Lion Bean的初始化不会立刻发生。也就是说,原型Bean不会随着IOC容器的启动而初始化。以下是启动容器但并未请求Bean的代码:

package com.example.demo.application;
​
import com.example.demo.configuration.PrototypeLifecycleConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class DemoApplication {
   
    public static void main(String[] args) {
   
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
                PrototypeLifecycleConfiguration.class);
    }
}
​

运行结果:

  当我们明确请求一个Lion2的实例时,我们会看到所有的初始化方法按照预定的顺序执行,这个顺序跟单例Bean完全一致:

package com.example.demo.application;
​
import com.example.demo.bean.Lion2;
import com.example.demo.configuration.PrototypeLifecycleConfiguration;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
​
public class DemoApplication {
​
    public static void main(String[] args) {
​
        System.out.println("Spring容器初始化开始");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
                PrototypeLifecycleConfiguration.class);
        System.out.println("Ready to get a Lion instance...");
        Lion2 lion = context.getBean(Lion2.class);
        System.out.println("A Lion instance has been fetched...");
        System.out.println("Lion instance is no longer needed, preparing to destroy...");
        context.getBeanFactory().destroyBean(lion);
        System.out.println("Lion instance has been destroyed...");
    }
}

运行结果:

可以看出:

在对 prototype Bean(原型 Bean)singleton Bean(单例 Bean) 的三种销毁方式进行对比实验后可以发现: 当通过 IOC 容器的 destroyBean() 方法手动销毁原型 Bean 时,只有使用 @PreDestroy 注解标注的方法以及实现了 DisposableBean 接口的 destroy() 方法会被正常调用,而通过 destroy-method 属性指定的自定义销毁方法并不会被执行。

由此可以得出结论:在原型 Bean 的销毁过程中,Spring 并不会触发由 destroy-method 配置的自定义销毁逻辑。这也说明,destroy-method 方式在原型 Bean 场景下存在一定的局限性。

因此,如果 Bean 在销毁阶段包含关键的资源释放或清理逻辑,更稳妥的做法是将这些逻辑放在 @PreDestroy 注解的方法中,或者实现 DisposableBean 接口的 destroy() 方法,以确保在原型 Bean 被销毁时能够得到正确执行。

6. Spring中控制Bean生命周期的三种方式总结

执行顺序代码依赖性容器支持单实例Bean原型Bean
init-method & destroy-method最后较低(依赖于Spring Bean配置,不侵入业务代码)xml、注解原生支持只支持 init-method
@PostConstruct & @PreDestroy最先中等(需要在业务代码中添加JSR规范的注解)注解原生支持,xml需开启注解驱动
InitializingBean & DisposableBean中间较高(需要业务代码实现Spring特定接口)xml、注解原生支持

7. 总结

到此这篇关于Spring中Bean的生命周期原理解析:实例化、属性赋值、初始化、运行期和销毁的文章就介绍到这了,更多相关Spring中Bean的生命周期原理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文