BeanPostProcessor接口定義回調方法,可以實現該方法來提供自己的實例化邏輯,依賴解析邏輯等。
也可以在Spring容器通過插入一個或多個BeanPostProcessor的實現來完成實例化,配置和初始化一個bean之后實現一些自定義邏輯回調方法。
可以配置多個BeanPostProcessor接口,通過設置BeanPostProcessor實現的Ordered接口提供的order屬性來控制這些BeanPostProcessor接口的執行順序。
ApplicationContext會自動檢測由BeanPostProcessor接口的實現定義的bean,注冊這些bean為后置處理器,然后通過在容器中創建bean,在適當的時候調用它。
示例:

public class HelloWorld { private String message; public void getMessage() { System.out.println("Your Message : " + message); } public void setMessage(String message) { this.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的之前和之后實現更復雜的邏輯,因為你有兩個訪問內置bean對象的后置處理程序的方法。

1 import org.springframework.beans.BeansException; 2 import org.springframework.beans.factory.config.BeanPostProcessor; 3 4 public class InitHelloWorld implements BeanPostProcessor { 5 6 @Override 7 public Object postProcessAfterInitialization(Object bean, String beanName) 8 throws BeansException { 9 System.out.println("After Initialization: " + beanName); 10 return bean; 11 } 12 13 @Override 14 public Object postProcessBeforeInitialization(Object bean, String beanName) 15 throws BeansException { 16 System.out.println("Before Initialization: " + beanName); 17 return bean; 18 } 19 20 }
MainApp.java文件中,需要注冊一個在AbstractApplicationContext類中聲明的關閉hook的registerShutdownHook()方法。它將確保正常關閉,並且調用相關的destroy()方法。

1 import org.springframework.context.support.AbstractApplicationContext; 2 import org.springframework.context.support.ClassPathXmlApplicationContext; 3 4 public class MainApp { 5 public static void main(String[] args) { 6 AbstractApplicationContext context = new ClassPathXmlApplicationContext( 7 "beans.xml"); 8 HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); 9 10 obj.getMessage(); 11 context.registerShutdownHook(); 12 } 13 }

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd"> 6 7 <bean id="helloWorld" class="com.microyum.HelloWorld" init-method="init" destroy-method="destroy"> 8 <property name="message" value="Hello World" /> 9 </bean> 10 11 <bean class="com.microyum.InitHelloWorld" /> 12 </beans>
執行結果:
Before Initialization: helloWorld
Bean is going through init.
After Initialization: helloWorld
Your Message : Hello World
Bean will destroy now.