Spring Bean 后置处理器PostProcessor

时间:2022-07-22
本文章向大家介绍Spring Bean 后置处理器PostProcessor,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

BeanPostProcessor 可以对 bean(或对象)实例进行操作,这意味着 Spring IoC 容器实例化一个 bean 实例,然后 BeanPostProcessor 接口进行它们的工作。

ApplicationContext 会自动检测由 BeanPostProcessor 接口的实现定义的 bean,注册这些 bean 为后置处理器,然后通过在容器中创建 bean,在适当的时候调用它。

看个非常简单的例子:在任何 bean 的初始化的之前和之后输入该 bean 的名称:

新建一个InitHelloWorld.java文件:

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
   }
}

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

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

</beans>

把InitHelloWorld配置到beans.xml里:

控制台输出:

constructor called!
Before Initialization : helloWorld
Bean is going through init.
After Initialization : helloWorld
Your Message : Hello World!
Bean will destroy now.

创建Spring IOC容器时,如果检测到PostProcessor,就调用其postProcessBeforeInitialization和postProcessAfterInitialization方法: