-
擴展點簡述
Factory hook that allows for custom modification of new bean instances — for example, checking for marker interfaces or wrapping beans with proxies. Typically, post-processors that populate beans via marker interfaces or the like will implement {@link #postProcessBeforeInitialization}, while post-processors that wrap beans with proxies will normally implement {@link #postProcessAfterInitialization}.
-
擴展點的生命周期及擴展點的執(zhí)行時機
屬于Bean的實例化階段擴展,針對于任何Bean的實例化兜辞。
執(zhí)行時機分別位于InitializingBean's afterPropertiesSet方法或者init-method之前和之后鹤耍,
此時Bean以及實例化完成,對象屬性已經注入弄跌。
-
擴展點的作用
對實例化Bean做進一步的處理,在擴展時機前后調用尝苇,把控好時機擴展就好铛只。
比如做一些注解配置的處理等埠胖,其他的博主暫時想不到有好的玩法/(ㄒoㄒ)/~~
-
擴展點實戰(zhàn)
/**
* BeanPostProcessor接口默認實現(xiàn)了postProcessBeforeInitialization和postProcessAfterInitialization兩個方法,
* 作用范圍:任何Bean實例化對象
* 方法執(zhí)行時機:參照各方法注釋
*/
@Component
public class TestBeanPostProcess implements BeanPostProcessor {
/**
* Apply this {@code BeanPostProcessor} to the given new bean instance <i>before</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method).
*
* 執(zhí)行時機:InitializingBean's afterPropertiesSet方法或者init-method之前執(zhí)行淳玩。
*/
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor-Before: " + beanName);
return bean;
}
/**
* Apply this {@code BeanPostProcessor} to the given new bean instance <i>after</i> any bean
* initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
* or a custom init-method).
* <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
* instance and the objects created by the FactoryBean (as of Spring 2.0).
*
* 執(zhí)行時機:InitializingBean's afterPropertiesSet方法或者init-method之后直撤。
*
* 注意:Spring2.0后,F(xiàn)actoryBean也要走這個方法蜕着。
*/
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("BeanPostProcessor-After: " + beanName);
return bean;
}
}
-
BeanPostProcessor的擴展資料
不僅可以實現(xiàn)BeanPostProcessor擴展谊惭,Spring還有一些他的子類也提供了擴展:
DestructionAwareBeanPostProcessor
在銷毀該BeanPostProcessor之前,將其應用于給定的bean實例侮东。
例如圈盔,調用自定義銷毀回調。像DisposableBean的destroy和自定義destroy方法一樣悄雅,
此回調僅適用于生命周期完全被容器管理的Bean驱敲。 單例和作用域bean通常是這種情況。InstantiationAwareBeanPostProcessor
添加了實例化之前的回調宽闲,以及在實例化之后但設置了顯式屬性或發(fā)生自動裝配之前的回調众眨。
通常用于抑制特定目標Bean的默認實例化,例如創(chuàng)建具有特殊TargetSource的代理(池目標容诬,延遲初始化目標等)娩梨,或實現(xiàn)其他注入策略,例如字段注入览徒。
但官方說這個一般應用于內部代碼狈定,所以擴展須掌握會具體影響到哪些Bean。
更多Spring擴展請查看專題Spring開發(fā)筆記习蓬。