前言 介面是Spring中一個非常重要的介面,它的介面定義如下 當你實現了這個介面的時候,Spring會保證在每一個bean對象初始化方法調用之前調用 方法,在初始化方法調用之後調用 的註冊 看過我之前寫的IOC源碼分析系列文章的同學應該對這個都比較有印象 ) Spring在執行到這的時候會把所有實 ...
前言
BeanPostProcessor
介面是Spring中一個非常重要的介面,它的介面定義如下
public interface BeanPostProcessor {
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
當你實現了這個介面的時候,Spring會保證在每一個bean對象初始化方法調用之前調用postProcessBeforeInitialization
方法,在初始化方法調用之後調用postProcessAfterInitialization
BeanPostProcessor
的註冊
看過我之前寫的IOC源碼分析系列文章的同學應該對這個都比較有印象
Spring在執行到這的時候會把所有實現BeanPostProcessor
介面的實現類都註冊到BeanFactory
中,一起來看一下實現的細節
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//獲取所有BeanPostProcessor的實現類
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 這裡把實現PriorityOrdered介面,Ordered 介面的BeanPostProcessors 和其他類型的BeanPostProcessors 區分開
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
//對實現了PriorityOrdered介面的按優先順序排序
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
//這裡就是註冊了,下麵會說
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(beanFactory, orderedPostProcessors);
//註冊
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
//註冊
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最後註冊常規的
sortPostProcessors(beanFactory, internalPostProcessors);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
可以看到上方的代碼就是把這些BeanPostProcessor
分為了幾類,然後分別根據規則排序後註冊進BeanFactory中,而BeanFactory中其實就只是維護了一個BeanPostProcessor
的列表而已
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList();
private static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {
for (BeanPostProcessor postProcessor : postProcessors) {
beanFactory.addBeanPostProcessor(postProcessor);
}
}
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
this.beanPostProcessors.remove(beanPostProcessor);
this.beanPostProcessors.add(beanPostProcessor);
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
}
執行原理
我們知道Bean的初始化是在定義在容器的刷新過程中,而具體的實現則是由AbstractAutowireCapableBeanFactory.initializeBean()
方法完成的。在這個方法中就包含了BeanPostProcessor
的調用邏輯
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// BeanPostProcessors 的Before 方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 調用初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// BeanPostProcessors 的After方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
而這裡面的執行邏輯我們也可以猜到,無非就是迴圈遍歷所有的BeanPostProcessor
,然後一一執行
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;}
其中applyBeanPostProcessorsAfterInitialization
的實現內容跟這個是一樣的
但是這裡面有一個主意的點,那就是如果具體的實現一但返回null,那麼就會跳出for迴圈,後面的就得不到機會執行了
常見用例
查看這個介面的繼承體系,可以看到這個介面的實現類是非常多的,各個實現類的功能如果感興趣大家可以去慢慢挖掘一下