Spring提供了不少擴展接口,BeanPostProcessor接口和InstantiationAwareBeanPostProcessor接口就是其中兩個。javascript
BeanPostProcessor接口做用是:若是咱們須要在Spring容器完成Bean的實例化、配置和其餘的初始化先後添加一些本身的邏輯處理,咱們就能夠定義一個或者多個BeanPostProcessor接口的實現,而後註冊到容器中。
java
Spring中Bean的實例化過程圖示:spring
由上圖能夠看到,Spring中的BeanPostProcessor在實例化過程處於的位置,BeanPostProcessor接口有兩個方法須要實 現:postProcessBeforeInitialization和 postProcessAfterInitialization,BeanPostProcessor接口定義以下:express
[javascript] view plaincopyapp
package org.springframework.beans.factory.config; post
import org.springframework.beans.BeansException; ui
public interface BeanPostProcessor { this
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; spa
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; .net
}
由方法名字也能夠看出,前者在實例化及依賴注入完成後、在任何初始化代碼(好比配置文件中的init-method)調用以前調用;後者在初始化代碼調用以後調用。
注意:
一、接口中的兩個方法都要將傳入的bean返回,而不能返回null,若是返回的是null那麼咱們經過getBean方法將得不到目標。
二、BeanFactory和ApplicationContext對待bean後置處理器稍有不一樣。ApplicationContext會自動檢測在 配置文件中實現了BeanPostProcessor接口的全部bean,並把它們註冊爲後置處理器,而後在容器建立bean的適當時候調用它,所以部署 一個後置處理器同部署其餘的bean並無什麼區別。而使用BeanFactory實現的時候,bean 後置處理器必須經過代碼顯式地去註冊,在IoC容器繼承體系中的ConfigurableBeanFactory接口中定義了註冊方法:
[java] view plaincopy
/** * Add a new BeanPostProcessor that will get applied to beans created * by this factory. To be invoked during factory configuration. * <p>Note: Post-processors submitted here will be applied in the order of * registration; any ordering semantics expressed through implementing the * {@link org.springframework.core.Ordered} interface will be ignored. Note * that autodetected post-processors (e.g. as beans in an ApplicationContext) * will always be applied after programmatically registered ones. * @param beanPostProcessor the post-processor to register */ void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
另外,不要將BeanPostProcessor標記爲延遲初始化。由於若是這樣作,Spring容器將不會註冊它們,自定義邏輯也就沒法獲得應用。假如 你在<beans />元素的定義中使用了'default-lazy-init'屬性,請確信你的各個BeanPostProcessor標記爲'lazy- init="false"'。
InstantiationAwareBeanPostProcessor是BeanPostProcessor的子接口,能夠在Bean生命週期的另外 兩個時期提供擴展的回調接口,即實例化Bean以前(調用postProcessBeforeInstantiation方法)和實例化Bean以後(調 用postProcessAfterInstantiation方法),該接口定義以下:
[java] view plaincopy
package org.springframework.beans.factory.config; import java.beans.PropertyDescriptor; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor { Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException; boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException; PropertyValues postProcessPropertyValues( PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException; }
其使用方法與上面介紹的BeanPostProcessor接口相似,只時回調時機不一樣。