本例子源於:W3CSchool,在此作記錄
Bean 后置處理器允許在調用初始化方法前后對 Bean 進行額外的處理。
BeanPostProcessor 接口定義回調方法,你可以實現該方法來提供自己的實例化邏輯,依賴解析邏輯等。你也可以在 Spring 容器通過插入一個或多個 BeanPostProcessor 的實現來完成實例化,配置和初始化一個bean之后實現一些自定義邏輯回調方法。
你可以配置多個 BeanPostProcessor 接口,通過設置 BeanPostProcessor 實現的 Ordered 接口提供的 order 屬性來控制這些 BeanPostProcessor 接口的執行順序。
BeanPostProcessor 可以對 bean(或對象)實例進行操作,這意味着 Spring IoC 容器實例化一個 bean 實例,然后 BeanPostProcessor 接口進行它們的工作。
ApplicationContext 會自動檢測由 BeanPostProcessor 接口的實現定義的 bean,注冊這些 bean 為后置處理器,然后通過在容器中創建 bean,在適當的時候調用它。
在你自定義的的BeanPostProcessor 接口實現類中,要實現以下的兩個抽象方法BeanPostProcessor.postProcessBeforeInitialization(Object, String) 和BeanPostProcessor.postProcessAfterInitialization(Object, String) 和,注意命名要准確
否則會出現: “ The type InitHelloWorld must implement the inherited abstract method BeanPostProcessor.postProcessBeforeInitialization(Object, String) ”之類的錯誤
相對於上個例子,在原來的基礎上新增一個BeanPostProcessor 接口實現類,在xml配置文件中添加該實現類對應的bean
BeanPostProcessor 接口實現類如下:
package com.how2java.w3cschool.beanlife; import org.springframework.beans.factory.config.BeanPostProcessor; public class InitHelloWorld implements BeanPostProcessor{ public Object postProcessBeforeInitialization(Object bean,String beanName) { System.out.println("BeforeInitialization:"+beanName); return bean; // you can return any other object as well
} public Object postProcessAfterInitialization(Object bean,String beanName) { System.out.println("AfterInitialization:"+beanName); return bean; // you can return any other object as well
} }
xml配置文件新增如下內容:
<bean class = "com.how2java.w3cschool.beanlife.InitHelloWorld"></bean>
輸出的結果如下: