Spring 简明教程

Spring - Bean Post Processors

BeanPostProcessor 接口定义回调方法,您可以实现这些方法以提供自己的实例化逻辑、依赖关系解析逻辑等。您还可以在 Spring 容器完成 bean 的实例化、配置和初始化后实现一些自定义逻辑,方法是插入一个或多个 BeanPostProcessor 实现。

The BeanPostProcessor interface defines callback methods that you can implement to provide your own instantiation logic, dependency-resolution logic, etc. You can also implement some custom logic after the Spring container finishes instantiating, configuring, and initializing a bean by plugging in one or more BeanPostProcessor implementations.

你可以配置多个 BeanPostProcessor 接口,并且可以通过设置 BeanPostProcessor 实现 Ordered 接口提供的 order 属性来控制这些 BeanPostProcessor 接口执行的顺序。

You can configure multiple BeanPostProcessor interfaces and you can control the order in which these BeanPostProcessor interfaces execute by setting the order property provided the BeanPostProcessor implements the Ordered interface.

在 Bean(或对象)实例上运行 BeanPostProcessor,这意味着 Spring IoC 容器实例化一个 Bean 实例,然后 BeanPostProcessor 接口执行它们的工作。

The BeanPostProcessors operate on bean (or object) instances, which means that the Spring IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their work.

ApplicationContext 会自动检测以 BeanPostProcessor 接口实现为定义的任何 bean,并注册这些 bean 作为后置处理器,然后由容器在 bean 创建时适时调用。

An ApplicationContext automatically detects any beans that are defined with the implementation of the BeanPostProcessor interface and registers these beans as postprocessors, to be then called appropriately by the container upon bean creation.

Example

以下示例展示如何在 ApplicationContext 的上下文中编写、注册和使用方法 BeanPostProcessor。

The following examples show how to write, register, and use BeanPostProcessors in the context of an ApplicationContext.

让我们准备一个可用的 Eclipse IDE,然后执行以下步骤来创建一个 Spring 应用程序−

Let us have a working Eclipse IDE in place and take the following steps to create a Spring application −

Steps

Description

1

Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.

2

Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.

3

Create Java classes HelloWorld, InitHelloWorld and MainApp under the com.tutorialspoint package.

4

Create Beans configuration file Beans.xml under the src folder.

5

The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

以下是 HelloWorld.java 文件的内容 −

Here is the content of HelloWorld.java file −

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy(){
      System.out.println("Bean will destroy now.");
   }
}

这是一个实现 BeanPostProcessor 的非常基本的示例,该示例在任何 bean 初始化之前和之后输出一个 bean 名称。你可以在初始化 bean 的前后实现更复杂的逻辑,因为你可以同时在 post 处理器方法中访问 bean 对象。

This is a very basic example of implementing BeanPostProcessor, which prints a bean name before and after initialization of any bean. You can implement more complex logic before and after intializing a bean because you have access on bean object inside both the post processor methods.

以下为 InitHelloWorld.java 文件内容−

Here is the content of InitHelloWorld.java file −

package com.tutorialspoint;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.BeansException;

public class InitHelloWorld implements BeanPostProcessor {
   public Object postProcessBeforeInitialization(Object bean, String beanName)
      throws BeansException {

      System.out.println("BeforeInitialization : " + beanName);
      return bean;  // you can return any other object as well
   }
   public Object postProcessAfterInitialization(Object bean, String beanName)
      throws BeansException {

      System.out.println("AfterInitialization : " + beanName);
      return bean;  // you can return any other object as well
   }
}

以下是 MainApp.java 文件的内容。在这里你需要注册 AbstractApplicationContext 类中声明的关机挂接 registerShutdownHook() 方法。这将确保正常关闭并调用相关的销毁方法。

Following is the content of the MainApp.java file. Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

package com.tutorialspoint;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}

以下是 init 方法和 destroy 方法所需的配置文件 Beans.xml

Following is the configuration file Beans.xml required for init and destroy methods −

<?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-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld"
      init-method = "init" destroy-method = "destroy">
      <property name = "message" value = "Hello World!"/>
   </bean>

   <bean class = "com.tutorialspoint.InitHelloWorld" />

</beans>

一旦你完成了创建源代码和 bean 配置文件,让我们运行该应用程序。如果你的应用程序一切正常,则将显示以下信息 −

Once you are done with creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

BeforeInitialization : helloWorld
Bean is going through init.
AfterInitialization : helloWorld
Your Message : Hello World!
Bean will destroy now.