本文是针对Srping的ClassPathXMLApplicationContext来进行源码解析,在本篇博客中将不会讲述spring Xml解析注册代码,由于ApplicationContext是BeanFactory的扩展版本,ApplicationContext的GetBean和xml解析注册BeanDefinition都是用一套代码,若是您是第一次看请先看一下XMLBeanFactory解析和BeanFactory.GetBean源码解析:html
- XMLBeanFactory源码解析地址:blog.csdn.net/qq_30257149…
- BeanFactory.getBean源码解析地址:blog.csdn.net/qq_30257149…
做者整理了spring-framework 5.x的源码注释,代码已经上传者做者的GitHub了,可让读者更好的理解,地址:git
- GItHub:github.com/lantaoGitHu…
package lantao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.lantao.UserBean;
public class ApplicationContextTest {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-bean.xml");
UserBean userBean = (UserBean) applicationContext.getBean("userBean");
System.out.println(userBean.getName());
}
}
复制代码
在这里直接使用ClassPathXmlApplicationContext进行xml解析,在这里xml解析的代码和GetBean的代码就不过多的描述了,ApplicationContext是BeanFactory的扩展,因此想要看这两部分源码的请看做者的上两篇博客Sprin源码解析; github
/**
* Create a new ClassPathXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of resource locations
* @param refresh whether to automatically refresh the context,
* loading all bean definitions and creating all singletons.
* Alternatively, call refresh manually after further configuring the context.
* @param parent the parent context
* @throws BeansException if context creation failed
* @see #refresh()
*/
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
// 支持解析多文件
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}复制代码
在setConfigLocations方法中将资源文件放入configLocations全局变量中,,而且支持多文件解析,接下来咱们你看一下重点,refresh方法;spring
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备刷新上下文
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 对beanFactory的各类功能填充,加载beanFactory,通过这个方法 applicationContext就有了BeanFactory的全部功能
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 对beanFactory进行各类功能填充
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 容许在context子类中对BeanFactory进行post-processing。
// 容许在上下文子类中对Bean工厂进行后处理
// 能够在这里进行 硬编码形式的 BeanFactoryPostProcessor 调用 addBeanFactoryPostProcessor
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 激活各类BeanFactory处理器 BeanFactoryPostProcessors是在实例化以前执行
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册 拦截Bean建立 的Bean处理器,这里只是注册,真正地调用在getBean的时候 BeanPostProcessors实在init方法先后执行 doCreateBean方法中的 实例化方法中执行
// BeanPostProcessor执行位置:doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//为上下文初始化Message源,(好比国际化处理) 这里没有过多深刻
initMessageSource();
// Initialize event multicaster for this context.
//初始化应用消息广播,并放入 applicationEventMulticaster bean中
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//留给子类来初始化其它的bean
onRefresh();
// Check for listener beans and register them.
//在全部注册的bean中查找Listener bean,注册到消息广播器中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//初始化剩下的单实例
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//完成刷新过程,通知生命周期护处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人(LifecycleProcessor 用来与全部声明的bean的周期作状态更新)
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.
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(); } } }复制代码
对于ApplicationContext来讲,refresh方法几乎涵盖了全部的基础和扩展功能,接下来看一下这个方法都作了什么;bash
- 刷新上下文,初始化前的准备工做;
- 加载beanFactory,通过这个方法 applicationContext就有了BeanFactory的全部功能
- 对beanFactory进行各类功能填充
- 容许在这里对BeanFactory的二次加工,例如:能够在这里进行硬编码方法的对BeanFactory进行BeanFactoryPostProcessor或BeanPostProcessor的操做;在这里简单说一下BeanFactoryPostProcessor是在bean实例化以前执行的,BeanPostProcessor是在初始化方法先后执行的,BeanFactoryPostProcessor操做的是BeanFactoryBeanPostProcessor操做的是Bean,其次这里还涉及了一个扩展BeanDefinitionRegistryPostProcessor它是继承了BeanFactoryPostProcessor,而且还有本身的定义方法 postProcessBeanDefinitionRegistry,这个方法能够操做BeanDefinitionRegistry,BeanDefinitionRegistry有个最主要的方法就是registerBeanDefinition,能够注册BeanDefinition,能够用这方法来处理一下不受spring管理的一下bean;
- 处理全部的BeanFactoryPostProcessor,也能够说是激活BeanFactory处理器,在这个方法里会先处理BeanDefinitionRegistryPostProcessor,在处理BeanFactoryPostProcessor,由于BeanDefinitionRegistryPostProcessor有本身的定义,因此先执行;
- 注册BeanPostProcessors ,这里只是注册,真正地调用在getBean的时候 BeanPostProcessors实在init方法先后执行 BeanPostProcessor执行位置:doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization方法中;
- 为上下文初始化Message源,(好比国际化处理) 这里没有过多深刻;
- 初始化应用消息广播,初始化 applicationEventMulticaster ,判断使用自定义的仍是默认的;
- 留给子类来初始化其它的bean;
- 在全部注册的bean中查找 ApplicationListener bean,注册到消息广播器中;
- 初始化剩下的单实例(非懒加载),这里会是涉及conversionService,LoadTimeWeaverAware,冻结BeanFactory,初始化Bean等操做;
- 完成刷新过程,包括 清除 下文级资源(例如扫描的元数据),通知生命周期护处理器lifecycleProcessor并strat,同时publish Event发出ContextRefreshEvent通知别人;
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
// 标志,指示是否已关闭此上下文
this.closed.set(false);
// 指示此上下文当前是否处于活动状态的标志
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 对上下文环境中的任何属性源进行分类。
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties,
//验证标示为必填的属性信息是否都有了 ConfigurablePropertyResolver#setRequiredProperties 方法
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}复制代码
一眼望去,可能以为这个方法没有作什么,其实这方法中除了Closed和Active最终要的是initPropertySources和getEnvironment().validateRequiredProperties()方法;app
- initPropertySources证符合Spring的开放式结构设计,给用户最大扩展Spring的能力。用户能够根据自身的须要重写initPropertySourece方法,并在方法中进行个性化的属性处理及设置。
- validateRequiredProperties则是对属性进行验证,那么如何验证呢?举个融合两句代码的小例子来理解。
例如如今有这样一个需求,工程在运行过程当中用到的某个设置(例如VAR)是从系统环境变量中取得的,而若是用户没有在系统环境变量中配置这个参数,工程不会工做。这一要求也各类各样许有的解决办法,在Spring中能够这么作,能够直接修改Spring的源码,例如修改ClassPathXmlApplicationContext.淡然,最好的办法是对源码进行扩展,能够自定义类:编辑器
public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext{ public MyClassPathXmlApplicationContext(String.. configLocations){ super(configLocations); } protected void initPropertySources(){ //添加验证要求 getEnvironment().setRequiredProterties("VAR"); } }复制代码
![]()
自定义了继承自ClassPathXmlApplicationContext的MyClassPathXmlApplicationContext,并重写了initPropertySources方法,在方法中添加了个性化需求,那么在验证的时候也就是程序走到getEnvironment().validateRequiredProperties()代码的时候,若是系统并无检测到对应VAR的环境变量,将抛出异常。固然咱们还须要在使用的时候替换掉原有的ClassPathXmlApplicationContext:ide
public static void main(Stirng[] args){ ApplicationContext bf = new MyClassPathXmlApplicationContext("myTest.xml"); User user = (User)bf.getBean("testBean"); }复制代码
![]()
上述案例来源于:Spring源码深度解析(第二版)141页;
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}复制代码
/**
* This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle.
*/
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
// createBeanFactory方法直接新建一个DefaultListableBeanFactory,内部使用的是DefaultListableBeanFactory实例
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 设置序列化id
beanFactory.setSerializationId(getId());
// 定制beanFactory工厂
customizeBeanFactory(beanFactory);
// 加载BeanDefinition
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
// 使用全局变量记录BeanFactory
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}复制代码
看一下上述方法都作了什么:工具
- 判断BeanFactory是否存在,若是存在则销毁全部Bean,而后关闭BeanFactory;
- 使用createBeanFactory方法直接新建一个DefaultListableBeanFactory,内部使用的是DefaultListableBeanFactory实例;
- 设置BeanFactory的设置序列化id
- 定制beanFactory工厂,也就是给allowBeanDefinitionOverriding(是否容许覆盖同名称的Bean)和allowCircularReferences(是否容许bean存在循环依赖),可经过setAllowBeanDefinitionOverriding和setAllowCircularReferences赋值,这里就可经过商编初始化方法中的initPropertySources方法来进行赋值;
package lantao; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyApplicationContext extends ClassPathXmlApplicationContext { public MyApplicationContext(String... configLocations){ super(configLocations); } protected void initPropertySources(){ //添加验证要求 getEnvironment().setRequiredProperties("VAR"); // 在这里添加set super.setAllowBeanDefinitionOverriding(true); super.setAllowCircularReferences(true); } } 复制代码
![]()
- 加载BeanDefinition,就是解析xml,循环解析,这里就不看了,若是不了解看做者上篇博客;
/**
* Configure the factory's standard context characteristics, * such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc. // 设置BeanFactory的classLoader为当前context的classloader beanFactory.setBeanClassLoader(getClassLoader()); // Spel语言解析器 // 设置BeanFactory的表达式语言处理器 Spring3中增长了表达式语言的支持 // 默承认以使用#{bean.xxx}的形式来调用相关属性值 // 在Bean实例化的时候回调用 属性填充的方法(doCreateBean 方法中的 populateBean 方法中的 applyPropertyValues 方法中的 evaluateBeanDefinitionString ) 就会判断beanExpressionResolver是否为null操做 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 为BeanFactory增长一个默认的 PropertyEditor 这个主要对bean的属性等设置管理的一个工具 增长属性注册编辑器 例如:bean property 类型 date 则须要这里 // beanFactory会在初始化 BeanWrapper(initBeanWrapper)中调用 ResourceEditorRegistrar 的 registerCustomEditors 方法 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. // ApplicationContextAwareProcessor --> postProcessBeforeInitialization // 注册 BeanPostProcessor BeanPostProcessor 实在实例化先后执行的 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 设置几个忽略自动装配的接口 在addBeanPostProcessor方法中已经对下面几个类作了处理,他们就不是普通的bean了,因此在这里spring作bean的依赖的时候忽略 // doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的 !isExcludedFromDependencyCheck(pd) 判断, // 在属性填充的时候回判断依赖,若是存在下属几个则不作处理 对于下面几个类能够作implements操做 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // 设置几个注册依赖 参考spring源码深度解析原文:当注册依赖解析后,例如但那个注册了对BeanFactory。class的解析依赖后,当bean的属性注入的时候,一旦检测到属性为BeanFactory的类型变回将beanFactory 实例注入进去 beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Register early post-processor for detecting inner beans as ApplicationListeners. // 寄存器早期处理器,用于检测做为ApplicationListener的内部bean。 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. // 增长了对AxpectJ的支持 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } // Register default environment beans. // 添加默认的系统环境bean if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }复制代码
不说废话,直接看这个方法都作了什么:post
- 设置BeanFactory的classLoader为当前context的classloader;
- 设置BeanFactory的表达式语言处理器 Spring3中增长了Spel表达式语言的支持, 默承认以使用#{bean.xxx}的形式来调用相关属性值,在Bean实例化的时候回调用 属性填充的方法(doCreateBean 方法中的 populateBean 方法中的 applyPropertyValues 方法中的 evaluateBeanDefinitionString ) 就会判断beanExpressionResolver是否为null操做,若是不是则会使用Spel表达式规则解析
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="testOneBean" class="lantao.bean.TestOneBean"> <property name="testTwoBean" value="#{testTWoBean}"/> </bean> <bean id="testTWoBean" class="lantao.bean.TestTwoBean"/> <!-- 上面 至关于 下边 --> <bean id="testOneBean1" class="lantao.bean.TestOneBean"> <property name="testTwoBean" ref="testTWoBean1"/> </bean> <bean id="testTWoBean1" class="lantao.bean.TestTwoBean"/> </beans>复制代码
![]()
- 为BeanFactory增长一个默认的 PropertyEditor 这个主要对bean的属性等设置管理的一个工具 增长属性注册编辑器 例如:User类中 startDate 类型 date 可是xml property的value是2019-10-10,在启动的时候就会报错,类型转换不成功,这里可使用继承PropertyEditorSupport这个类机型重写并注入便可使用;beanFactory会在初始化BeanWrapper (initBeanWrapper)中调用 ResourceEditorRegistrar 的 registerCustomEditors 方法进行初始化;
- 配置BeanPostProcessor,这里配置的是ApplicationContextAwareProcessor,上边咱们说了,BeanPostProcessor是在初始化方法Init先后执行,看一下ApplicationContextAwareProcessor的Before和After方法:
@Override @Nullable public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException { AccessControlContext acc = null; // 该方法也会在 BeanFactory 实例化bean 中调用 doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization --> postProcessBeforeInitialization // 若是实例化的类实现了 invokeAwareInterfaces 方法中的判断类 则会调用初始方法赋值 if (System.getSecurityManager() != null && (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware || bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) { acc = this.applicationContext.getBeanFactory().getAccessControlContext(); } if (acc != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareInterfaces(bean); return null; }, acc); } else { invokeAwareInterfaces(bean); } return bean; } private void invokeAwareInterfaces(Object bean) { if (bean instanceof Aware) { if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext); } } } @Override public Object postProcessAfterInitialization(Object bean, String beanName) { return bean; } 复制代码
![]()
在Before方法中调用了invokeAwareInterfaces方法,在invokeAwareInterfaces方法中作了类型 instanceof 的判断,意思就是若是这个Bean实现了上述的Aware,则会初始会一下资源,好比实现了ApplicationContextAware,就会setApplicationContext,这里相信你们都用过,就很少说了;
- 设置几个忽略自动装配的接口 在addBeanPostProcessor方法中已经对下面几个类作了处理,他们就不是普通的bean了,因此在这里spring作bean的依赖的时候忽略,在doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的 !isExcludedFromDependencyCheck(pd) 判断,若是存在则不作依赖注入了;
- 设置几个注册依赖 参考spring源码深度解析原文:当注册依赖解析后,例如当注册了对BeanFactory的解析依赖后,当bean的属性注入的时候,一旦检测到属性为BeanFactory的类型便会将beanFactory 实例注入进去;
- 添加BeanPostProcessor,这里是添加ApplicationListener,是寄存器早期处理器;这里能够看做者的源码测试,在spring-context的test测试类下有;
- 增长了对AxpectJ的支持
- 注册默认的系统环境bean,environment ,systemProperties,systemEnvironment;
postProcessBeanFactory方法是个空方法,容许在上下文子类中对Bean工厂进行后处理,例如:能够在这里进行 硬编码形式的 BeanFactoryPostProcessor 调用 addBeanFactoryPostProcessor,进行addBeanFactoryPostProcessor或者是BeanPostProcessor;
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
// 对 BeanDefinitionRegistry 类型处理
if (beanFactory instanceof BeanDefinitionRegistry) {
// 强转
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 普通的处理器
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
//注册处理器
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 这里就是硬编码处理 由于这里是从 getBeanFactoryPostProcessors()方法获取的 能够硬编码从addBeanFactoryPostProcessor()方法添加
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 对于 BeanDefinitionRegistryPostProcessor 类型 在 BeanFactoryPostProcessor 的基础上还有本身的定义,须要先调用
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
// 执行 继承 BeanDefinitionRegistryPostProcessor 类的 postProcessBeanDefinitionRegistry 方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
//上边的For循环只是调用了硬编码的 BeanDefinitionRegistryPostProcessor 中的 postProcessBeanDefinitionRegistry 方法,
// 可是 BeanFactoryPostProcessor 中的 postProcessBeanFactory 方法尚未调用,是在方法的最后一行
// invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); 这两个方法中执行的,
// 下面是自动处理器 获取类型是BeanDefinitionRegistryPostProcessor beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 获取的
// 当前注册处理器
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 首先调用实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 执行 BeanDefinitionRegistryPostProcessor类的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 下一个 ,调用实现 Ordered 的 BeanDefinitionRegistryPostProcessors
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 执行 BeanDefinitionRegistryPostProcessor类的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 最后,调用全部其余BeanDefinitionRegistryPostProcessors,直到再也不显示其余BeanDefinitionRegistryPostProcessors 无序的
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 执行 BeanDefinitionRegistryPostProcessor类的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// 如今,调用到目前为止处理的全部处理器的 执行BeanFactoryPostProcessor 类的 postProcessBeanFactory 方法
// 这里执行的是 硬编码 和 非硬编码(自动)的 BeanFactoryPostProcessor 类的 postProcessBeanFactory 方法 分为硬编码处理器 和 普通处理器
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// 调用在上下文实例中注册的工厂处理器的postProcessBeanFactory方法。 就是硬编码 经过 addBeanFactoryPostProcessor 方法添加的BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 自动处理 非硬编码 获取类型为是BeanFactoryPostProcessor beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// 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.
// 实现 priorityOrdered 的
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 实现 Ordered 的
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(priorityOrderedPostProcessors, beanFactory);
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(orderedPostProcessors, beanFactory);
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();
}
复制代码
上述代码看起来不少,可是总计起来就三件事:
- 执行硬编码的和主动注入的BeanDefinitionRegistryPostProcessor,调用postProcessBeanDefinitionRegistry方法;
- 执行硬编码的和主动注入的BeanFactoryPostProcessor,调用postProcessBeanFactory方法;
- 自动注入的可继承Ordered排序,priorityOrdered排序或无序;
上述测试在做者的spring源码congtext中lantao包下有测试用例;
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.
// 使用 priorityOrdered保证顺序
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// MergedBeanDefinitionPostProcessor
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 使用order保证顺序
List<String> orderedPostProcessorNames = new ArrayList<>();
// 无序的
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 进行add操做
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.
// 首先 注册实现PriorityOrdered的 BeanPostProcessors 先排序PostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 下一个,注册实现Ordered的BeanPostProcessors
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(orderedPostProcessors, beanFactory);
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.
// 最后,注册全部MergedBeanDefinitionPostProcessor类型的BeanPostProcessor,并不是重复注册。
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 添加 ApplicationListener探测器
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}复制代码
registerBeanPostProcessors方法代码仍是比较长的,它和invokeBeanFactoryPostProcessors方法最主要的区别就是registerBeanPostProcessors只在这里注册,但不在这里调用,作的事情和invokeBeanFactoryPostProcessors差很少:
- 使用priorityOrdered,Ordered或无序保证顺序;
- 经过beanFactory.addBeanPostProcessor(postProcessor)进行注册;
很简单,代码篇幅很长,可是很好理解,这里能够简单看一下;
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 使用自定义的 广播
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 使用spring 默认的广播
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
复制代码
initApplicationEventMulticaster方法中主要就是判断是使用自定义的ApplicationEventMulticaster(广播器)仍是使用呢Spring默认的SimpleApplicationEventMulticaster广播器;
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans. */ protected void registerListeners() { // Register statically specified listeners first. // 注册 添加 ApplicationListener 这里经过硬编码 addApplicationListener 方法添加的 for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 注册 添加 ApplicationListener 这里是自动注册添加的 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... // 发布早期的事件 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }复制代码
registerListeners方法作了三件事情:
- 添加 ApplicationListener 这里经过硬编码 addApplicationListener 方法添加的;
- 添加 ApplicationListener 是经过自动注册添加的
- 发布早起事件
/**
* Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. // conversionService 用于类型转换 ,好比 String 转Date //判断BeanFactory中是否存在名称为“conversionService”且类型为ConversionService的Bean,若是存在则将其注入到beanFactory // 判断有无自定义属性转换服务接口,并将其初始化,咱们在分析bean的属性填充过程当中,曾经用到过该服务接口。在TypeConverterDelegate类的convertIfNecessary方法中 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } // Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. // 获得全部的实现了LoadTimeWeaverAware接口的子类名称,初始化它们 // 若是有LoadTimeWeaverAware类型的bean则初始化,用来加载Spring Bean时织入第三方模块,如AspectJ,咱们在后面详细讲解。 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // Stop using the temporary ClassLoader for type matching. // 中止使用临时类加载器 就是在这里不让使用呢 ClassLoader 了 beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes. // 冻结全部bean定义,说明你注册的bean将不被修改或进行任何进一步的处理 就是不让改了 BeanDefinition beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. // 初始化全部非懒加载的 单例 bean 调用你getBean方法 beanFactory.preInstantiateSingletons(); } 复制代码
finishBeanFactoryInitialization方法作了五件事情:
- 设置BeanFactory的conversionService,conversionService用于类型转换使用, 例如:User类中 startDate 类型 date 可是xml property的value是2019-10-10,在启动的时候就会报错,类型转换不成功,可使用conversionService;书中170页有具体代码;
- 添加BeanFactory的addEmbeddedValueResolver,读取配置信息放到这里,能够经过EmbeddedValueResolverAware来获取,参考:www.cnblogs.com/winkey4986/…
- 获得全部的实现了LoadTimeWeaverAware接口的子类名称,初始化它们,用来加载Spring Bean时织入第三方模块,如AspectJ,咱们在后面详细讲解。
- 中止使用临时类加载器 就是在这里不让使用呢 ClassLoader 了
- 冻结全部bean定义,说明你注册的bean将不被修改或进行任何进一步的处理 就是不让改了 BeanDefinition
- 初始化全部非懒加载的 单例 bean 调用你getBean方法,循环全部bean并实例化 条件是:单例,非Abstract 非懒加载
/**
* Finish the refresh of this context, invoking the LifecycleProcessor's * onRefresh() method and publishing the * {@link org.springframework.context.event.ContextRefreshedEvent}. */ protected void finishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). // 清除 下文级资源(例如扫描的元数据)。 clearResourceCaches(); // Initialize lifecycle processor for this context. // 在当前context中初始化 lifecycle // lifecycle 有本身的 start/ stop方法,实现此接口后spring保证在启动的时候调用start方法开始生命周期 关闭的时候调用 stop方法结束生命周期 initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. // onRefresh 启动全部实现了 lifecycle 的方法 getLifecycleProcessor().onRefresh(); // Publish the final event. // 当ApplicationContext初始化完成发布后发布事件 处理后续事宜 publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. // 这里 没明白》。。 LiveBeansView.registerApplicationContext(this); } 复制代码
finishRefresh方法是ApplicationContext初始化的最后一个方法了,他作了一些结尾的事情:
- 清除 下文级资源(例如扫描的元数据)。
- 在当前context中初始化 lifecycle,lifecycle 有本身的 start/ stop方法,实现此接口后spring保证在启动的时候调用start方法开始生命周期 关闭的时候调用 stop方法结束生命周期。
- onRefresh 启动全部实现了 lifecycle 的方法,调用了start方法。
- 当ApplicationContext初始化完成发布事件 处理后续事宜。
- LiveBeansView.registerApplicationContext(this)这个代码没有太明白,有大神能够留言;
至此ApplicationContext的源码就都已经分析完成了,其中有不少地方很难懂,你们能够对应着源码一块儿看,会好理解一些,若是其中有错误,欢迎大神指点,在下方留言,本篇博客是做者参考SPring 源码深度解析 + 本身的理解写出来的,算是一个学习后的的产出,最后,码字不易,转载请注明出处。
地址:https://juejin.im/editor/drafts/5c8c8174f265da2db912b519 或 https://mp.csdn.net/postedit/88224879