目录
2. 理解 init-method 和 destroy-method
3. @PostConstruct 和 @PreDestroy
3.1 示例:@PostConstruct 和 @PreDestroy 的使用
3.2 初始化和销毁 —— 注解和 init-method 共存对比
4. 实现 InitializingBean 和 DisposableBean 接口
4.1 示例:实现 InitializingBean 和 DisposableBean 接口
6. Spring 中控制 Bean 生命周期的三种方式总结
1. 理解 Bean 的生命周期
1.1 生命周期的各个阶段
在 Spring IOC 容器中,Bean 的生命周期大致如下:
- 实例化:当启动 Spring 应用时,IOC 容器就会为在配置文件中声明的每个 <bean> 创建一个实例。
- 属性赋值:实例化后,Spring 就通过反射机制给 Bean 的属性赋值。
- 调用初始化方法:如果 Bean 配置了初始化方法,Spring 就会调用它。初始化方法是在 Bean 创建并赋值之后调用,可以在这个方法里面写一些业务处理代码或者做一些初始化的工作。
- Bean 运行期:此时,Bean 已经准备好被程序使用了,它已经被初始化并赋值完成。
- 应用程序关闭:当关闭 IOC 容器时,Spring 会处理配置了销毁方法的 Bean。
- 调用销毁方法:如果 Bean 配置了销毁方法,Spring 会在所有 Bean 都已经使用完毕,且 IOC 容器关闭之前调用它,可以在销毁方法里面做一些资源释放的工作,比如关闭连接、清理缓存等。
这就是 Spring IOC 容器管理 Bean 的生命周期,帮助我们管理对象的创建和销毁,以及在适当的时机做适当的事情。
我们可以将生命周期的触发称为回调,因为生命周期的方法是我们自己定义的,但方法的调用是由框架内部帮我们完成的,所以可以称之为 “回调”。
2. 理解 init-method 和 destroy-method
让我们先了解一种最容易理解的生命周期阶段:初始化和销毁方法。这些方法可以在 Bean 的初始化和销毁阶段起作用,我们通过示例来演示这种方式。
为了方便演示 XML 和注解的方式,接下来我们会创建两个类来分别进行演示,分别为 Lion 和 Elephant,让我们一步一步对比观察。
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容器已关闭。");
}
}
运行结果
在 <bean> 标签中,有两个属性:init-method 和 destroy-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 注解中也有类似的属性:initMethod 和 destroyMethod,这两个属性的作用与 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 中定义了一个相同 id 或 name 的 Bean,那么最后注册的那个 Bean 会覆盖之前注册的,这取决于配置文件加载顺序,无论在 Java 配置中还是 XML 配置中定义的 initMethod 或 destroyMethod,最后生效的总是后加载的配置中定义的。
“init-method” 是指定初始化回调方法的属性的统称,无论它是在 XML 配置还是 Java 配置中使用。同样地,“destroy-method” 是指定销毁回调方法的属性的统称。后文我们讲解多种声明周期共存的时候,将延续这种说法。
2.3 初始化和销毁方法的特性
在 Spring 框架中配置 Bean 的初始化和销毁方法时,需要按照 Spring 的规范来配置这些方法,否则 Spring 可能无法正确地调用它们。下面给每个特性提供一个解释和示例:
1、方法的访问权限无限制:这意味着无论方法是 public、protected 还是 private,Spring 都可以调用。Spring 通过反射来调用这些方法,所以它可以忽略 Java 的访问权限限制。示例:
public class MyBean {
private void init() {
// 初始化代码
}
}
在上述代码中,即使 init 方法是 private 的,Spring 也可以正常调用。
2、方法没有参数:由于 Spring 不知道需要传递什么参数给这些方法,所以这些方法不能有参数。示例:
public class MyBean {
public void init() {
// 初始化代码
}
}
在上述代码中,init 方法没有参数,如果添加了参数,如 public void init (String arg),Spring 将无法调用此方法。
3、方法没有返回值:由于返回的值对 Spring 来说没有意义,所以这些方法不应该有返回值。示例:
public class MyBean {
public void init() {
// 初始化代码
}
}
在上述代码中,init 方法是 void 的,如果让此方法返回一个值,如 public String init (),那么 Spring 将忽略此返回值。
4、方法可以抛出异常:如果在初始化或销毁过程中发生错误,这些方法可以抛出异常来通知 Spring。示例:
public class MyBean {
public void init() throws Exception {
// 初始化代码
if (somethingGoesWrong) {
throw new Exception("Initialization failed.");
}
}
}
在上述代码中,如果在 init 方法中的初始化代码出错,它会抛出一个异常。Spring 框架默认会停止 Bean 的创建,并抛出异常。
2.4 探究 Bean 的初始化流程顺序
在上面的代码中,我们可以看出 Bean 在 IOC 容器初始化阶段就已经创建并初始化了,那么每个 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容器已关闭。");
}
}
运行结果
我们可以得出结论:在 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容器已关闭。");
}
}
运行结果
这里可以看到 @PostConstruct 和 @PreDestroy 注解正确地应用在了 Lion 的初始化和销毁过程中。
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 注解的 initMethod 和 destroyMethod 属性。
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 生命周期的三种方式是:
- 使用 Spring 的 init-method 和 destroy-method(在 XML 配置或者 Java 配置中自定义的初始化和销毁方法);
- 使用 JSR-250 规范的 @PostConstruct 和 @PreDestroy 注解;
- 实现 Spring 的 InitializingBean 和 DisposableBean 接口。
接下来我们测试一下,一个 Bean 同时定义 init-method、destroy-method 方法,使用 @PostConstruct、@PreDestroy 注解,以及实现 InitializingBean、DisposableBean 接口,执行顺序是怎样的。
我们创建一个新的类 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 生命周期的流程:
- 实例化(通过构造器方法);
- 设置 Bean 的属性(通过 setter 方法);
- 调用 Bean 的初始化方法(@PostConstruct、afterPropertiesSet 方法或者 init-method 指定的方法);
- Bean 可以被应用程序使用;
- 当容器关闭时,调用 Bean 的销毁方法(@PreDestroy、destroy 方法或者 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 - 狮子行动结束。。。");
}
}
然后在 Spring 的 Java 配置中声明并设定其为原型 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...");
}
}
运行结果:
将原型 Bean 和单例 Bean 的三种生命周期进行对比后发现,调用 IOC 容器的 destroyBean () 方法销毁原型 Bean 时,只有 @PreDestroy 注解和 DisposableBean 接口的 destroy 方法会被触发,而被 destroy-method 标记的自定义销毁方法并不会被执行。
从这里我们可以得出结论:在销毁原型 Bean 时,Spring 不会执行由 destroy-method 标记的自定义销毁方法,所以原型 Bean 的 destroy-method 的也有局限性。如果有重要的清理逻辑需要在 Bean 销毁时执行,那么应该将这部分逻辑放在 @PreDestroy 注解的方法或 DisposableBean 接口的 destroy 方法中。