Spring原始碼分析之BeanPostProcessor介面和BeanFactoryPostProcessor介面方法不執行原因分析
阿新 • • 發佈:2019-02-15
首先下面是我的Bean
/* * Copyright 2002-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.verify.constant; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.*; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import java.beans.PropertyDescriptor; /** * TODO * * @author linjiedeng * @date 17/5/8 下午10:47 * @since TODO */ public class StudentService implements BeanPostProcessor, InitializingBean, BeanFactoryPostProcessor, BeanNameAware, BeanClassLoaderAware, BeanFactoryAware { private ClassLoader classLoader; private BeanFactory beanFactory; private String name; @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; //實現BeanClassLoaderAware介面可以獲取到對應的classLoader System.out.println("set bean class loader"); System.out.println(classLoader); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; //實現BeanFactoryAware介面獲取該Bean的beanFactory System.out.println("set bean factory"); System.out.println(beanFactory); } @Override public void setBeanName(String name) { this.name = name; //實現BeanNameAware介面獲取該Bean的名字 System.out.println("set bean name"); System.out.println(name); } public void initMethod() { System.out.println("init method"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet"); } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessBeforeInitialization"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("postProcessAfterInitialization"); return bean; } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { System.out.println("postProcessBeanFactory"); } public void read() { System.out.println("Student service read"); } }
bean的配置檔案applicationContext.xml內容如下:
測試程式碼如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="studentService" class="com.verify.constant.StudentService" init-method="initMethod"/> </beans>
@Test public void test2() { ClassPathResource resource = new ClassPathResource("applicationContext.xml"); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory); reader.loadBeanDefinitions(resource); StudentService studentService = (StudentService)factory.getBean("studentService"); studentService.read(); }
測試程式碼執行後,其他方法都執行了,但是唯獨BeanPostProcessor介面的兩個方法postProcessBeforeInitialization和postProcessAfterInitialization以及
BeanFactoryPostProcessor介面的方法沒有執行,這我就有點疑惑了,這是咋回事?其實這兩個介面應該是在bean初始化的過程中被呼叫,是在AbstractAutowireCapableBeanFactory介面的initializeBean初始化方法中被呼叫的,程式碼如下:
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()) {
//執行BeanPostProcessor擴充套件點的PostProcessBeforeInitialization進行修改例項化Bean
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//呼叫Bean的初始化方法,這個初始化方法是在BeanDefinition中通過定義init-method屬性指定的
//同時,如果Bean實現了InitializingBean介面,那麼這個Bean的afterPropertiesSet實現也不會被呼叫
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()) {
//執行BeanPostProcessor擴充套件點的PostProcessAfterInitialization進行修改例項化Bean
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
initializeBean方法是Bean的初始化方法,在該初始化方法中會呼叫Bean的一些初始化方法,比如如下方法:
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
即只要Bean實現了BeanNameAware介面,這裡就會幫你呼叫,BeanClassLoaderAware和BeanFactory介面同樣如此,上述我的程式碼中就實現了這三個介面,啟動的過程中都被呼叫了,再實現的方法中可以獲取這些資訊,並存儲。
再比如如下方法:
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;
}
這裡其實是如果Bean實現了BeanPostProcessor介面,這裡就會呼叫bean實現的postProcessBeforeInitialization方法,這是在bean的真正初始化之前被呼叫
對應的BeanPostProcessor介面的另外一個方法,是在bean的初始化之後被呼叫,如下:
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
真正的初始化是在如下方法:
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet(); //啟動afterPropertiesSet,afterPropertiesSet是InitializingBean介面的方法
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName(); //獲取使用者自定義的初始化方法
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd); //呼叫自定義的初始化方法
}
}
}
可以看到,上述程式碼實際上是在呼叫Bean實現的initializingBean介面的afterPropertiesSet方法來初始化Bean,接下來還呼叫了使用者自定義的init-method方法,可以看到上面我的applicationContext.xml配置檔案中配置的有一個initMethod方法,這就是自定義的初始化方法,這個方法也是在這裡被呼叫的
好,程式碼分析到這,也可以看到了,既然這裡初始化的時候呼叫了BeanPostProcessor的那兩個方法,但是我的測試程式碼為什麼沒有執行這兩個方法呢?
其實可以看到真正執行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;
}
其中的getBeanPostProcessors()方法獲取的實際就是AbstractBeanFactory的this.beanPostProcessors屬性值,看來是這個屬性值為空,所以執行的時候沒有呼叫
那接下來要分析的原因就是為什麼this.beanPostProcessors屬性值為空呢?或者說bean的載入時為什麼沒有載入進來呢?那就要看它是在哪裡載入的了,最終定位到載入是在
AbstractApplicationContext中執行的
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
//這是在子類中啟動refreshBeanFactory的地方
// 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.
// 設定BeanFactory的後置處理
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 呼叫BeanFactory的後處理器,這些後處理器是在Bean定義中向容器註冊的
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 註冊Bean的後處理器,在Bean建立過程中呼叫
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 對上下文中的訊息源進行初始化
initMessageSource();
// Initialize event multicaster for this context.
// 初始化上下文中的事件機制
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 初始化其他的特殊Bean
onRefresh();
// Check for listener beans and register them.
// 檢查監聽Bean,並且將這些Bean向容器註冊
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.這裡是對lazy-init屬性進行處理的地方
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 釋出容器事件,結束Refresh過程
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
// 為防止Bean資環佔用,在異常處理中,銷燬已經在前面過程中生成的單件Bean
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
registerBeanPostProcessors(beanFactory)是載入Bean實現的BeanPostProcessor介面,具體載入程式碼如下:
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
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);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
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);
// Now, register all regular BeanPostProcessors.
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);
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(beanFactory, internalPostProcessors);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
invokeBeanFactoryPostProcessors(beanFactory)是載入Bean實現的BeanFactoryPostProcessor介面,具體載入如下:
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
new LinkedList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryPostProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
registryPostProcessors.add(registryPostProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
registryPostProcessors.addAll(priorityOrderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(beanFactory, orderedPostProcessors);
registryPostProcessors.addAll(orderedPostProcessors);
invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
registryPostProcessors.add(pp);
processedBeans.add(ppName);
pp.postProcessBeanDefinitionRegistry(registry);
reiterate = true;
}
}
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(beanFactory, orderedPostProcessors);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
所以我們可以看到BeanPostProcessor介面和BeanFactoryPostProcessor介面的載入只在abstractApplicationContext中執行了,而在DefaultListableBeanFactory
中沒有執行,而我們測試用的工廠就是DefaultListableBeanFactory,所以實際是根本沒有載入上面兩個介面。
接下來我把測試程式碼換成如下:
@Test
public void test3() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentService studentService = (StudentService)applicationContext.getBean("studentService");
studentService.read();
}
然後執行,可以很清楚的看到那兩個介面的方法都執行了。
原因是:ClassPathXmlApplicationContext是abstractApplicationContext的實現,所以使用這個工廠來管理bean,會載入如上兩個介面。
總結:
其實我們兩個測試程式碼分別使用了DefaultListableBeanFactory和ClassPathXmlApplicationContext作為Bean工廠,ClassPathXmlApplicationContext底層其實
也是使用的DefaultListableBeanFactory作為Bean工廠,但是ClassPathXmlApplicationContext在DefaultListableBeanFactory的基礎上額外載入了
BeanPostProcessor介面和BeanFactoryPostProcessor介面,這個載入是在其父介面AbstractApplicationContext中執行的,這就是為什麼test2測試程式碼不執行這兩個介面的方法的原因。
此外,對於兩個工廠而言,真正的在初始化的過程中呼叫這些介面的地方都是在底層工廠DefaultListableBeanFactory中,而DefaultListableBeanFactory 實際是呼叫的父介面AbstractAutowireCapableBeanFactory的initializeBean方法來進行初始化,從而呼叫那些初始化介面的方法