javascript
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/beanshttp://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方法:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
 
總結
以上是生活随笔為你收集整理的Spring Bean 后置处理器PostProcessor的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Spring里的容器和Bean对象
- 下一篇: LG 新能源 Q1 营收 8.75 万亿
