Spring 5 InitializingBean 和 DisposableBean 示例

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

在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

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>net.javaguides.spring</groupId>
    <artifactId>spring-bean-lifecycle</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>  
    </dependencies>
    <build>
     <sourceDirectory>src/main/java</sourceDirectory>
         <plugins>
            <plugin>
               <artifactId>maven-compiler-plugin</artifactId>
               <version>3.5.1</version>
               <configuration>
                   <source>1.8</source>
                   <target>1.8</target>
               </configuration>
           </plugin>
         </plugins>
     </build>
</project>

考虑DatabaseInitiaizer类,实现InitializingBeanDisposableBean接口。

DatabaseInitiaizer.java

package net.javaguides.spring;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class DatabaseInitiaizer implements InitializingBean, DisposableBean {

    private List < User > listOfUsers = new ArrayList < > ();

    @Override
    public void afterPropertiesSet() throws Exception {
        User user = new User(1, "User");
        User user1 = new User(2, "Admin");
        User user2 = new User(3, "SuperAdmin");

        listOfUsers.add(user);
        listOfUsers.add(user1);
        listOfUsers.add(user2);
        System.out.println("-----------List of users added in init() method ------------");
        for (Iterator < User > iterator = listOfUsers.iterator(); iterator.hasNext();) {
            User user3 = (User) iterator.next();
            System.out.println(user3.toString());
        }
        // save to database
    }

    @Override
    public void destroy() {
        // Delete from database
        listOfUsers.clear();
        System.out.println("-----------After of users removed from List in destroy() method ------------");
        for (Iterator < User > iterator = listOfUsers.iterator(); iterator.hasNext();) {
            User user3 = (User) iterator.next();
            System.out.println(user3.toString());
        }
        System.out.println("List is clean up ..");
    }
}

创建POJO - User.java

package net.javaguides.spring;

public class User {
    private Integer id;
    private String name;

    public User() {}

    public User(Integer id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + "]";
    }
}

基于注解的配置 - AppConfig.java

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

package net.javaguides.spring;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "net.javaguides.spring")
public class AppConfig {
 
}

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

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

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

package net.javaguides.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Application {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        context.close();
    }
}

输出

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

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

相关文章