使用BeanFactoryPostProcessor這種姿勢不要用
前言
在公司內(nèi),Spring基本都是首選的IOC框架,Spring也提供了很多擴展點讓我們介入到容器的生命周期中龙填,例如BeanFactoryPostProcessor氧急、BeanPostProcessor等。今天就記錄下BeanFactoryPostProcessor的一種不正確用法八回。
約定
實例化:instantiation
初始化:initialization
BeanFactoryPostProcessor的作用
首先貼下BeanFactoryPostProcessor的源碼吧
/**
* Allows for custom modification of an application context's bean definitions,
* adapting the bean property values of the context's underlying bean factory.
*
* <p>Application contexts can auto-detect BeanFactoryPostProcessor beans in
* their bean definitions and apply them before any other beans get created.
*
* <p>Useful for custom config files targeted at system administrators that
* override bean properties configured in the application context.
*
* <p>See PropertyResourceConfigurer and its concrete implementations
* for out-of-the-box solutions that address such configuration needs.
*
* <p>A BeanFactoryPostProcessor may interact with and modify bean
* definitions, but never bean instances. Doing so may cause premature bean
* instantiation, violating the container and causing unintended side-effects.
* If bean instance interaction is required, consider implementing
* {@link BeanPostProcessor} instead.
*
* @author Juergen Hoeller
* @since 06.07.2003
* @see BeanPostProcessor
* @see PropertyResourceConfigurer
*/
public interface BeanFactoryPostProcessor {
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for overriding or adding
* properties even to eager-initializing beans.
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}
首先請一字一句通讀一下doc酷愧,其中兩句話非常重要:
- BeanFactoryPostProcessor允許使用者修改容器中的bean definitions
- BeanFactoryPostProcessor可以與bean definitions打交道,但是千萬不要進(jìn)行bean實例化(感覺這里應(yīng)該說的是不要在BeanFactoryPostProcessor進(jìn)行可能觸發(fā)bean實例化的操作)缠诅。這么做可能會導(dǎo)致bean被提前實例化溶浴,會破壞容器造成預(yù)估不到的副作用。如果你需要hack到bean實例化過程滴铅,請考慮使用BeanPostProcessor戳葵。
從doc中可以讀到,BeanFactoryPostProcessor的主要作用是讓你能接觸到bean definitions汉匙,對bean definitions進(jìn)行一定hack拱烁,但是也僅此而已了。絕對不允許在BeanFactoryPostProcessor中觸發(fā)到bean的實例化X洹O纷浴! 為啥呢伤锚,doc說得很清楚but never bean instances. Doing so may cause premature bean instantiation, violating the container and causing unintended side-effects. 下面就列舉錯誤使用造成的兩種典型“副作用”擅笔。
副作用1——使用注解進(jìn)行依賴注入失敗
貼一下示例代碼片段吧。
@Component
public class PrematureBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
Map<String, BBean> map = beanFactory.getBeansOfType(BBean.class);
for (BBean bBean : map.values()) {
assert bBean.getABean() == null;
}
}
}
@Component("bBean")
public class BBean {
@Autowired
private ABean aBean;
public ABean getABean() {
return aBean;
}
}
@Component
public class ABean {
private String name = "a";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
如上demo所示屯援,在運行后猛们,BBean中被期待注入的ABean最終為null。這是為啥呢狞洋?
貼一段ApplicationContext的啟動代碼吧
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
可以看到的是postProcessBeanFactory(beanFactory); 首先invoke了容器中的BeanFactoryPostProcessor實現(xiàn)類弯淘,其中當(dāng)然就包括PrematureBeanFactoryPostProcessor,此時通過beanFactory.getBeansOfType觸發(fā)了bean提前實例化吉懊。按理說庐橙,bean提前實例化也應(yīng)該沒問題的,aBean也應(yīng)該是能夠被注入的呀借嗽!那為啥最終不是這個結(jié)果呢态鳖。讓我們研究下@Resource @AutoWired這種注解是如何注入依賴的,如何起作用的就明白了恶导。@AutoWired起作用依賴AutowiredAnnotationBeanPostProcessor,@Resource依賴CommonAnnotationBeanPostProcessor浆竭,這倆都是BeanPostProcessor的實現(xiàn)。那BeanPostProcessors在何處被spring invoke呢,參見registerBeanPostProcessors(beanFactory);在postProcessBeanFactory(beanFactory); 后面被調(diào)用兆蕉,也就是說BBean被觸發(fā)提前初始化的時候羽戒,AutowiredAnnotationBeanPostProcessor還沒有被注冊自然也不會被執(zhí)行到,自然ABean=null虎韵。
PS:如果ABean和BBean都是通過xml的方式配置的則不會有上述問題(因為會執(zhí)行setter setProperty)易稠,但強烈不建議這么做!
副作用2——可能會將ApplicationContext容器啟動過程暴露在多線程之下
“將ApplicationContext容器啟動過程暴露在多線程之下”倒不完全是因為錯誤使用BeanFactoryPostProcessor包蓝,而是錯上加錯驶社。假設(shè)我們發(fā)現(xiàn)在副作用1的場景下aBean無法注入,而將BBean通過如下方式修改
@Component("bBean")
public class BBean implements ApplicationContextAware {
private ApplicationContext context;
@Autowired
private ABean aBean;
public ABean getABean() {
return (ABean)context.getBean("aBean");
}
@Override
public String toString() {
return "BBean{" +
"aBean=" + aBean +
'}';
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}
這樣問題就更大了测萎,雖然在大多數(shù)的場景下不會有問題亡电。但是如果BBean是類似于像DTS processer bean或者像是MetaQ的 listener bean情況就非常糟糕了。這種bean一旦被實例化+初始化之后就可以接受請求硅瞧,如果在請求處理代碼中觸發(fā)了Spring bean的實例化過程份乒,則此時的容器會被破壞,結(jié)果是無法預(yù)知的腕唧。而且問題和可能不太容易復(fù)現(xiàn)或辖,因為只有在spring啟動過程中請求進(jìn)來觸發(fā)ABean首次實例化才有可能會發(fā)生錯誤。強烈要求MetaQ listener DTSprocesser等bean依賴容器自身的依賴注入枣接,不要認(rèn)為干擾颂暇;如果實在要用listener or processor 中使用context.getBean("aBean")的方式,那也請做好listener or processor 的生命周期管理但惶,保證在容器徹底起來之后才開始處理請求
總結(jié)
本文列舉了BeanFactoryPostProcessor錯誤使用可能造成的問題耳鸯。認(rèn)真讀doc,共勉膀曾!