Spring高手之路5——彻底掌握Bean的生命周期

这篇具有很好参考价值的文章主要介绍了Spring高手之路5——彻底掌握Bean的生命周期。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1. 理解Bean的生命周期

1.1 生命周期的各个阶段

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容器已关闭。");
    }
}

运行结果

Spring高手之路5——彻底掌握Bean的生命周期

<bean>标签中,有两个属性:init-methoddestroy-method,这两个属性用于指定初始化和销毁方法。

这里"simba has been initialized...“,证明init()方法被调用了。当context.close()被调用时,看到"simba has been destroyed...”,证明destroy()方法被调用了。

IOC 容器初始化之前,默认情况下 Bean 已经创建好了,而且完成了初始化动作;容器调用销毁动作时,先销毁所有 Bean ,最后 IOC 容器全部销毁完成。

这个例子通过一个简单的Spring应用程序显示了Spring bean的生命周期。我们可以在创建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高手之路5——彻底掌握Bean的生命周期

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

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

2.3 初始化和销毁方法的特性

Spring框架中配置Bean的初始化和销毁方法时,需要按照Spring的规范来配置这些方法,否则Spring可能无法正确地调用它们。下面给每个特性提供一个解释和示例:

  1. 方法的访问权限无限制:无论方法是publicprotectedprivate,还是default(包私有),Spring都可以调用。Spring通过反射来调用这些方法,所以它可以忽略Java的访问权限限制。示例:
public class MyBean {
    private void init() {
        // 初始化代码
    }
}

在上述代码中,即使init方法是private的,Spring也可以正常调用。

  1. 方法没有参数:由于Spring不知道需要传递什么参数给这些方法,所以这些方法不能有参数。示例:
public class MyBean {
    public void init() {
        // 初始化代码
    }
}

  Spring允许这些方法具有参数,Spring容器会尝试使用它的自动装配特性,通过类型或名称匹配找到合适的bean来作为参数进行调用。但是如果Spring无法找到匹配的bean或有多个匹配的bean,那么会在应用启动时抛出异常。

  1. 方法没有返回值:由于返回的值对Spring来说没有意义,所以这些方法不应该有返回值。示例:
public class MyBean {
    public void init() {
        // 初始化代码
    }
}

在上述代码中,init方法是void的,如果让此方法返回一个值,如public String init(),那么Spring将忽略此返回值。

  1. 方法可以抛出异常:如果在初始化或销毁过程中发生错误,这些方法可以抛出异常来通知Spring。示例:
public class MyBean {
    public void init() throws Exception {
        // 初始化代码
        if (somethingGoesWrong) {
            throw new Exception("Initialization failed.");
        }
    }
}

  在上述代码中,如果在init方法中的初始化代码出错,它会抛出一个异常。不管是调用初始化还是销毁方法,只要抛出了异常(无论是检查型异常还是未检查型异常),这些异常将被Spring容器捕获并封装为BeanCreationExceptionBeanDestructionException后抛出,这会导致Bean的创建或销毁过程失败。

  1. 方法不应是静态的:由于Spring需要一个Bean实例来调用初始化或销毁方法,静态方法属于类级别,不依赖于实例。如果标注在一个静态方法上,就失去了作用于实例生命周期的意义。比如:
public class MyBean {
    public static void init() {
        // 初始化代码
    }
}

  如果指定的初始化或销毁方法是静态的,Spring并不会报错,但是这违背了初始化和销毁方法应该是实例级别的原则。

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容器已关闭。");
    }
}

运行结果

Spring高手之路5——彻底掌握Bean的生命周期

我们可以得出结论:Bean的生命周期中,首先进行属性赋值,然后执行init-method标记的方法。


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;

@Component
public class Lion {

    private String name;

    public void setName(String name) {
        this.name = name;
    }

    @PostConstruct
    public void init() {
        System.out.println("Lion is going through init.");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("Lion is going through destroy.");
    }

    @Override
    public 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容器已关闭。");
    }
}

运行结果

Spring高手之路5——彻底掌握Bean的生命周期

这里可以看到@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容器已关闭。");
    }
}

运行结果

Spring高手之路5——彻底掌握Bean的生命周期

这里可以看到@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容器已关闭。");
    }
}

运行结果:

Spring高手之路5——彻底掌握Bean的生命周期

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高手之路5——彻底掌握Bean的生命周期

从上面的结果,我们可以得出以下结论,在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);
    }
}

运行结果:

Spring高手之路5——彻底掌握Bean的生命周期

  当我们明确请求一个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...");
    }
}

运行结果:

Spring高手之路5——彻底掌握Bean的生命周期

  将原型Bean和单例Bean的三种生命周期进行对比后发现,调用IOC容器的destroyBean()方法销毁原型Bean时,只有@PreDestroy注解和DisposableBean接口的destroy方法会被触发,而被destroy-method标记的自定义销毁方法并不会被执行。

  从这里我们可以得出结论:在销毁原型Bean时,Spring不会执行由destroy-method标记的自定义销毁方法,所以原型Beandestroy-method的也有局限性。如果有重要的清理逻辑需要在Bean销毁时执行,那么应该将这部分逻辑放在@PreDestroy注解的方法或DisposableBean接口的destroy方法中。文章来源地址https://www.toymoban.com/news/detail-492857.html


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

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


欢迎一键三连~

有问题请留言,大家一起探讨学习

----------------------Talk is cheap, show me the code-----------------------

到了这里,关于Spring高手之路5——彻底掌握Bean的生命周期的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring高手之路8——Spring Bean模块装配的艺术:@Import详解

      在 Spring 中,手动装配通常是指通过 XML 配置文件明确指定 Bean 及其依赖,或者在代码中直接使用 new 创建对象并设定依赖关系。   然而,随着 Spring 2.0 引入注解,以及 Spring 3.0 全面支持注解驱动开发,这个过程变得更加自动化。例如,通过使用 @Component + @Compo

    2024年02月13日
    浏览(24)
  • Spring bean 生命周期

    在互联网领域中,Spring框架扮演着重要的角色。作为一个开源的Java应用程序开发框架,Spring提供了一种灵活而强大的方式来构建可扩展的应用程序。Spring框架中的一个重要概念是Bean,它是Spring应用程序的基本构建块之一。了解Spring Bean的生命周期对于充分利用Spring框架的功能

    2024年02月11日
    浏览(35)
  • Spring:Bean生命周期

    Bean 生命周期 是 bean 对象从创建到销毁的整个过程。 简单的 Bean 生命周期的过程: 1.实例化(调用构造方法对 bean 进行实例化) 2.依赖注入(调用 set 方法对 bean 进行赋值) 3.初始化(手动配置 xml 文件中 bean 标签的 init-method 属性值,来指定调用对应的初始化方法) 4.使用

    2024年02月13日
    浏览(31)
  • 【Spring】—— bean生命周期

    1、初始化容器 1)创建对象(分配内存) 2)执行构造方法 3)执行属性注入(set操作) 4)执行bean初始化方法 2、使用bean 1)执行业务操作 3、关闭/销毁容器 1)执行bean销毁方法

    2024年02月02日
    浏览(34)
  • 【Spring】Bean的作用域与生命周期详情:请简述Spring的执行流程并分析Bean的生命周期?

     我们都知道,Spring框架为开发人员提供了很多便捷,这使得开发人员能够更加专注于应用程序的核心业务逻辑,而不需要花费大量时间和精力在技术细节上。作为一个包含众多工具方法的IoC容器,存取JavaBean是其极为重要的一个环节。本文就对Spring中的Bean的作用域和生命周

    2024年02月12日
    浏览(38)
  • Spring高手之路9——掌握Spring条件装配的秘密武器

      在 Spring 框架中,条件装配( Conditional Configuration )是一个非常重要的特性,它允许开发者根据满足的条件,动态地进行 Bean 的注册或是创建。这样就可以根据不同的环境或配置,创建不同的 Bean 实例,这一特性对于创建可配置和模块化的应用是非常有用的。 Spring 提供了一

    2024年02月16日
    浏览(31)
  • 【spring】spring bean的生命周期

    spring bean的生命周期 简介 本文测试并且介绍了spring中bean的生命周期,如果只想知道结果可以跳到最后一部分直接查看。 一、bean的创建阶段 spring中的bean是何时创建的? 在spring中有一个非常重要的注解,叫做**@Scope**,这个注解是用来控制spring中的bean是否是单例的,一般情况

    2024年02月15日
    浏览(35)
  • Spring Bean的生命周期

    Bean生命周期的整个执行过程描述如下: 1、根据配置情况调用Bean构造方法或工厂方法实例化 Bean。 2、利用依赖注入完成Bean中所有属性值的配置注入。 3、如果Bean 实现了BeanNameAware 接口,则 Spring调用Bean的setBeanName()方法传入当前Bean的id值。 4、如果Bean实现了BeanFactoryAware 接口

    2023年04月22日
    浏览(53)
  • Spring -- Bean的生命周期

    Spring容器在进行实例化时,会将xml配置的bean的信息封装成一个BeanDefinition对象,Spring根据BeanDefinition来创建Bean对象,里面有很多的属性用来描述Bean   BeanDefinition 中几个重要方法如下 beanClassName:bean 的类名 initMethodName:初始化方法名称 properryValues:bean 的属性值 scope:作用域

    2024年02月15日
    浏览(39)
  • Spring整理-Spring Bean的生命周期

    Spring Bean的生命周期涉及多个阶段,从Bean的定义到其销毁。在这个过程中,Spring容器负责创建、初始化、使用和最终销毁Bean。了解这个生命周期有助于更好地管理Bean的行为和资源使用。 实例化(Instantiation): 容器首先创建Bean的实例。 填充属性(Populate Properties): 容器

    2024年01月21日
    浏览(37)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包