Spring 5 InitializingBean 和 DisposableBean 示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(5.0k)|赞(0)|评价(0)|浏览(837)

在Spring中,为了与容器对Bean生命周期的管理进行交互,你可以实现Spring InitializingBeanDisposableBean接口。容器为前者调用afterPropertiesSet(),为后者调用destroy(),让Bean在初始化和销毁时执行某些动作。

JSR-250的@PostConstruct和@PreDestroy注解通常被认为是在现代Spring应用程序中接收生命周期回调的最佳实践。使用这些注解意味着你的Bean不会被耦合到Spring特定的接口。 
查看Spring @PostConstruct和@PreDestroy示例

  1. 对于实现了InitializingBean的Bean,它将在所有Bean属性都被设置后运行afterPropertiesSet()
  2. 对于实现了DisposableBean的Bean,它将在Spring容器释放Bean后运行destroy()

在本文中,我们使用最新发布的Spring 5.1.0.RELEASE版本来演示这个例子。

Spring InitializingBean和DisposableBean示例

在实时项目中,我们会在应用程序启动时用一些记录填充一个数据库表,并在应用程序关闭时从同一数据库表中删除记录。

在这个例子中,我们将使用afterPropertiesSet()方法在应用程序启动时向内存中的List数据结构填充一些用户对象。在应用程序关闭期间,我们还将使用destroy()方法从Listd中删除用户对象。

使用的工具和技术

  • Spring Framework - 5.1.0.RELEASE
  • JDK - 8或更高版本
  • Maven - 3.2以上
  • IDE - Eclipse Mars/STS

创建一个简单的Maven项目

使用你喜欢的IDE创建一个简单的Maven项目,关于打包结构请参考下面的章节。如果你是maven新手,请阅读本文《如何创建一个简单的Maven项目》。

项目结构

下图显示了项目结构,供您参考。 

the pom.xml File

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>net.javaguides.spring</groupId>
  6. <artifactId>spring-bean-lifecycle</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <url>http://maven.apache.org</url>
  9. <properties>
  10. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  11. </properties>
  12. <dependencies>
  13. <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
  14. <dependency>
  15. <groupId>org.springframework</groupId>
  16. <artifactId>spring-context</artifactId>
  17. <version>5.1.0.RELEASE</version>
  18. </dependency>
  19. </dependencies>
  20. <build>
  21. <sourceDirectory>src/main/java</sourceDirectory>
  22. <plugins>
  23. <plugin>
  24. <artifactId>maven-compiler-plugin</artifactId>
  25. <version>3.5.1</version>
  26. <configuration>
  27. <source>1.8</source>
  28. <target>1.8</target>
  29. </configuration>
  30. </plugin>
  31. </plugins>
  32. </build>
  33. </project>

考虑DatabaseInitiaizer类,实现InitializingBeanDisposableBean接口。

DatabaseInitiaizer.java

  1. package net.javaguides.spring;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import org.springframework.beans.factory.DisposableBean;
  6. import org.springframework.beans.factory.InitializingBean;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. public class DatabaseInitiaizer implements InitializingBean, DisposableBean {
  10. private List < User > listOfUsers = new ArrayList < > ();
  11. @Override
  12. public void afterPropertiesSet() throws Exception {
  13. User user = new User(1, "User");
  14. User user1 = new User(2, "Admin");
  15. User user2 = new User(3, "SuperAdmin");
  16. listOfUsers.add(user);
  17. listOfUsers.add(user1);
  18. listOfUsers.add(user2);
  19. System.out.println("-----------List of users added in init() method ------------");
  20. for (Iterator < User > iterator = listOfUsers.iterator(); iterator.hasNext();) {
  21. User user3 = (User) iterator.next();
  22. System.out.println(user3.toString());
  23. }
  24. // save to database
  25. }
  26. @Override
  27. public void destroy() {
  28. // Delete from database
  29. listOfUsers.clear();
  30. System.out.println("-----------After of users removed from List in destroy() method ------------");
  31. for (Iterator < User > iterator = listOfUsers.iterator(); iterator.hasNext();) {
  32. User user3 = (User) iterator.next();
  33. System.out.println(user3.toString());
  34. }
  35. System.out.println("List is clean up ..");
  36. }
  37. }

创建POJO - User.java

  1. package net.javaguides.spring;
  2. public class User {
  3. private Integer id;
  4. private String name;
  5. public User() {}
  6. public User(Integer id, String name) {
  7. super();
  8. this.id = id;
  9. this.name = name;
  10. }
  11. public Integer getId() {
  12. return id;
  13. }
  14. public void setId(Integer id) {
  15. this.id = id;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. @Override
  24. public String toString() {
  25. return "User [id=" + id + ", name=" + name + "]";
  26. }
  27. }

基于注解的配置 - AppConfig.java

创建AppConfig类,并在其中编写以下代码。

  1. package net.javaguides.spring;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. @ComponentScan(basePackages = "net.javaguides.spring")
  6. public class AppConfig {
  7. }

注意 - @ComponentScan注解会扫描所有的Bean,这些Bean的类被@Component注解放在一个由basePackages属性指定的包中。

运行中的Spring应用程序 - Application.java

让我们创建一个主类并运行一个应用程序。

  1. package net.javaguides.spring;
  2. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  3. public class Application {
  4. public static void main(String[] args) {
  5. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
  6. context.close();
  7. }
  8. }

输出

  1. -----------List of users added in init() method ------------
  2. User [id=1, name=User]
  3. User [id=2, name=Admin]
  4. User [id=3, name=SuperAdmin]
  5. -----------After of users removed from List in destroy() method -------
  6. List is clean up ..

JSR-250的@PostConstruct和@PreDestroy注解通常被认为是在现代Spring应用程序中接收生命周期回调的最佳实践。使用这些注解意味着你的Bean不会被耦合到Spring特定的接口。详见使用@PostConstruct和@PreDestroy。这个例子的源代码可以在我的GitHub仓库https://github.com/RameshMF/spring-core-tutorial中找到。

相关文章