/*
设置文件路径
刷新上下文
*/
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
//设置文件路径
setConfigLocations(configLocations);
if (refresh) {
//刷新上下文
refresh();
}
}
//解析路径
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
//解析路径,如果存在${var},会搜寻匹配的系统变量并替换
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
/*
准备刷新上下文环境
初始化beanFactory
对BeanFactory进行各种功能填充
子类覆盖方法做额外处理
执行所有BeanFactoryPostProcessors
注册BeanPostProcessors
国际化处理
初始化应用消息广播器
留给子类来初始化其他bean
注册监听器
初始化非惰性的剩下的单实例
完成刷新过程
异常处理
销毁已经创建的单例bean,避免资源悬空
标记没有正在刷新状态
抛出异常
重置缓存
*/
@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,并进行XML读取,加载BeanDefinition
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//对BeanFactory进行各种功能填充
//如@Qualifier与@Autowired
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//子类覆盖方法做额外处理
postProcessBeanFactory(beanFactory);
/*
BeanFactoryPostProcessors和BeanPostProcessors区别
BeanPostProcessors并不需要马山调用,所以不需要考虑硬编码方式
而BeanFactoryPostProcessors之所以考虑硬编码是因为不仅要实现注册功能,还要实现对后处理器的激活操作,所以需要载入配置中的定义,并进行激活
*/
// Invoke factory processors registered as beans in the context.
//激活各种BeanFactory处理器
//BeanFactoryPostProcessor作用域容器级,仅仅对容器中的bean进行后置处理,如propertyPlaceholderConfig,继承order可实现排序调用功能
//BeanFactoryPostProcessor可以修改实际的bean实例
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册拦截bean创建的bean处理器,这里只是注册,真正调用在getBean
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//为上下文初始化message源,即国际化处理
initMessageSource();
// Initialize event multicaster for this context.
//初始化应用消息广播器,并放入applicationEventMulticaster,bean中。
//SimpleApplicationEventMulticaster.multicastEvent:调用这个发送
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通知别人
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,避免资源悬空
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...
//重置Spring核心中的常见内省缓存,因为可能不再需要singleton bean的元数据了。。。
resetCommonCaches();
}
}
}
/*
设置上下文状态
留给子类初始化上下文环境变量,包括系统变量
验证需要的属性文件是否都已经放入环境中
在刷新之前初始或重置监听器
在多主机设置之前发布的ApplicationEvents。
*/
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
//验证需要的属性文件是否都已经放入环境中,当检测占位符资源无法解析,异常
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
//在刷新之前初始化本地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...
//在多主机设置之前发布的ApplicationEvents。
this.earlyApplicationEvents = new LinkedHashSet<>();
}
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//初始化BeanFactory,并进行XML文件读取,并将得到的BeanFactory记录在当前实体的属性中
refreshBeanFactory();
//返回当前实体的beanFactory属性
return getBeanFactory();
}
/*
销毁存在的BeanFactory
创建DefaultListableBeanFactory
序列化指定值
设置BeanFactory相关属性
加载BeanDefinition
使用全局变量记录BeanFactory实例
*/
@Override
protected final void refreshBeanFactory() throws BeansException {
//是否有BeanFactory
if (hasBeanFactory()) {
//销毁所有bean
destroyBeans();
//清除所有BeanFactory
closeBeanFactory();
}
try {
//创建DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//为了序列化指定id,如果需要的话让这个BeanFactory从id反序列化到BeanFactory对象
beanFactory.setSerializationId(getId());
//设置BeanFactory相关属性,包括是否允许覆盖同名称的不同定义的对象以及循环依赖
customizeBeanFactory(beanFactory);
//加载BeanDefinition,进行XML文件读取及解析,
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);
}
}
/*
设置是否允许覆盖同名称的不同定义的对象
设置是否允许bean之间存在循环依赖
一般子类继承修改这2值
*/
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
//一般子类继承修改这2值
//是否允许覆盖同名称的不同定义的对象
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
//是否允许bean之间存在循环依赖
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}
/*
为指定beanFactory创建XmlBeanDefinitionReader
设置环境变量
设置资源加载器
设置xml解析器
是否关闭XML验证
加载BeanDefinitions
*/
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//为指定beanFactory创建XmlBeanDefinitionReader
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//设置环境变量
beanDefinitionReader.setEnvironment(this.getEnvironment());
//设置资源加载器
beanDefinitionReader.setResourceLoader(this);
//设置xml解析器
//BeansDtdResolver:使用默认的DTD解析
//PluggableSchemaResolver:设置META-INF/spring.schemas路径,该文件有xsd路径地址
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
//对beanDefinitionReader设置,可以覆盖
//是否关闭XML验证,如XSD,DTD之类的验证
initBeanDefinitionReader(beanDefinitionReader);
//加载BeanDefinitions,内部调用XML解析
loadBeanDefinitions(beanDefinitionReader);
}
/*
解析Resource
*/
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
/*
设置加载器
设置表达式语言处理器
设置默认属性编辑器
添加BeanPostProcessor,对其他资源获取处理
设置忽略资源获取自动装配的接口
设置自动装配的特殊规则
添加BeanPostProcessor,销毁前回调
增加AspectJ支持
设置默认系统环境bean
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
//设置加载器
beanFactory.setBeanClassLoader(getClassLoader());
//设置表达式语言处理器,spring3.X新增,可以使用#{bean.xxx}调用相关属性值,支持SPEL表达式
//DefaultListableBeanFactory.doResolveDependency 调用 evaluateBeanDefinitionString
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//设置默认属性编辑器
//AbstractBeanFactory.initBeanWrapper会使用编辑器,对应AbstractBeanFactory.propertyEditorRegistrars
//registerBeanPostProcessors会注册所有自定义编辑器,对应AbstractBeanFactory.customEditors
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//添加BeanPostProcessor,主要对一些Aware资源获取的补充
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//设置忽略了几个自动装配的接口,因为继承这些Aware接的,将获得资源,ApplicationContextAwareProcessor注入了这些资源
//而且他主要是资源获取,不提供注入作用
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.
//设置自动装配的特殊规则,依赖类型如果是key,直接赋值value
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.
//添加BeanPostProcessor,主要用于销毁前回调
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
//增加AspectJ支持 LTW,静态注入aop
//LoadTimeWeaverBeanDefinitionParser.getBeanClassName注入了bean
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());
}
}
自定义属性编辑器传送门
/*
移除,重新添加
初始化bean前回调
销毁前回调bean
*/
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
//移除,重新添加
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
//初始化bean前回调
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
//销毁前回调bean
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
this.beanPostProcessors.add(beanPostProcessor);
}
/*
主要获取资源
*/
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
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 {
//实现这些Aware,将获得某些资源
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);
}
}
}
/*
执行BeanFactoryPostProcessors
对LTW的支持
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//执行BeanFactoryPostProcessors
//getBeanFactoryPostProcessors里面的BeanFactoryPostProcessor元素由addBeanFactoryPostProcessor执行的时候添加
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
//对LTW的支持
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
/*
对BeanDefinitionRegistry类型的处理
遍历所有硬编码注册的beanFactoryPostProcessors
当为BeanDefinitionRegistryPostProcessor类型
则执行postProcessBeanDefinitionRegistry
并添加注册处理器集合
不符合直接添加常规后置处理器
遍历配置文件注入的BeanDefinitionRegistryPostProcessor
保存继承PriorityOrdered排序接口的对象
按照PriorityOrdered排序当前处理器
添加所有的当前注册处理器到注册处理器中
当前处理器执行执行postProcessBeanDefinitionRegistry方法
清空当前注册处理器
遍历配置文件注入的BeanDefinitionRegistryPostProcessor
保存继承Ordered排序接口的对象
按照Ordered排序当前处理器
添加所有的当前注册处理器到注册处理器中
当前处理器执行执行postProcessBeanDefinitionRegistry方法
清空当前注册处理器
循环遍历以及调用postProcessBeanDefinitionRegistry方法
...
调用所有的继承了BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法
调用传来的postProcessBeanFactory的postProcessBeanFactory方法
获取所有继承了BeanFactoryPostProcessor的接口,并分别排序,和无序调用
清除缓存的合并bean定义
*/
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;
//记录通过硬编码方式注册的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
//记录通过硬编码方式注册的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//对于BeanDefinitionRegistryPostProcessor类型,在beanFactoryPostProcessor的基础上还有自己定义的方法,需要先调用
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
//执行postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
//记录常规beanFactoryPostProcessor
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.
//配置文件注入的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//按照优先级排序
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//ppName对应的class是否是PriorityOrdered的子类
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//按照PriorityOrdered排序当前处理器
sortPostProcessors(currentRegistryProcessors, beanFactory);
//添加所有的当前注册处理器到注册处理器中
registryProcessors.addAll(currentRegistryProcessors);
//当前处理器执行执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空当前注册处理器
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
//按照Ordered排序
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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// 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)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
//调用所有的继承了postProcessBeanFactory的postProcessBeanFactory方法
//硬编码设置的BeanFactoryPostProcessors
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//配置的BeanFactoryPostProcessors
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
//调用所有的继承了postProcessBeanFactory的postProcessBeanFactory方法
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!
//对于配置中读取的BeanFactoryPostProcessor的处理,实际从RootBeanDefinition获取类型匹配
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(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
//按照order排序调用
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...
//清除缓存的合并bean定义,因为后处理器可能已修改原始元数据,例如替换值中的占位符。。。
//清空已经标记(alreadyCreated)创建好的Bean, markBeanAsCreated方法标记创建的
beanFactory.clearMetadataCache();
}
/*
同上invokeBeanFactoryPostProcessors
但不同的是,这里主要是注册,而且添加了ApplicationListenerDetector
而上面的只会执行,而不会注册,因为生命周期不同
*/
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//获取所有继承了BeanPostProcessor的names
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;
/*
BeanPostProcessorChecker:普通信息打印
当spring配置中的后处理器还没有被注册就已经开始了bean的初始化时
便会打印BeanPostProcessorChecker设定信息
*/
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<>();
//使用Ordered保证顺序
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) {
//重复添加priorityOrderedPostProcessors和internalPostProcessors,在后续做了校验处理,所以不会重复添加
//为了分类层次更加明显估计
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
//注册所有实现priorityOrderedPostProcessors的BeanPostProcessors
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.
//注册所有无序的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类型的BeanPostProcessors,并非重复注册
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));
}
添加internalPostProcessors的时候会重复添加priorityOrderedPostProcessors
/*
移除,避免重新添加
标记有初始化bean前回调
标记有销毁前回调bean
添加集合末端
*/
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
//移除,避免重新添加
this.beanPostProcessors.remove(beanPostProcessor);
// Track whether it is instantiation/destruction aware
//标记有初始化bean前回调
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
//标记有销毁前回调bean
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
// Add to end of list
//添加集合末端
this.beanPostProcessors.add(beanPostProcessor);
}
初始化应用消息广播器
/*
注册默认applicationEventMulticaster监听器
*/
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 {
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() + "]");
}
}
}
/*
注册硬编码和配置文件注册的监听器处理
通知早期注入的事件
*/
protected void registerListeners() {
// Register statically specified listeners first.
//硬编码方式注册的监听器处理
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!
//配置文件注册的监听器处理
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);
}
}
}
初始化剩下的非延迟初始化单实例
/*
自定义转换器Conver
注册默认的嵌入式值解析器
初始化LTW
停止使用临时加载器类型匹配
冻结所有的bean定义
初始化剩下的单实例(非懒加载)
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
//自定义转换器Conver,名字必须conversionService
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.
// 如果在此之前没有任何bean后处理器(如propertyplaceholderconfigurerbean)注册,
// 则注册默认的嵌入式值解析器:此时,主要是为了在注释属性值中进行解析。
if (!beanFactory.hasEmbeddedValueResolver()) {//要应用的字符串解析器,例如用于注释属性值。
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
//初始化LTW
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
//停止使用临时加载器类型匹配
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
//冻结所有的bean定义,说明注册的bean定义将不被修改或任何进一步的处理
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
//初始化剩下的单实例(非懒加载)
beanFactory.preInstantiateSingletons();
}
/*
加载所有非抽象,非懒加载,且单例的对象
针对实现了SmartFactoryBean的工厂bean特别处理
针对实现了SmartInitializingSingleton接口的执行初始化后方法
*/
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//非抽象,非懒加载,且单例
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//是否工厂Bean
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
//是否迫切初始化
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
//初始化
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
//初始化后回调接口
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
完成刷新
/*
清除资源缓存
初始化LifecycleProcessor
启动所有实现了Lifecycle的bean
推送监听器.
...
*/
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
//清除资源缓存
clearResourceCaches();
// Initialize lifecycle processor for this context.
//初始化LifecycleProcessor
//spring启动LifecycleProcessor的时候调用start,关闭的时候调用stop,通常用来配置后台程序,如MQ轮询
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
//启动所有实现了Lifecycle的bean
getLifecycleProcessor().onRefresh();
// Publish the final event.
//推送监听器.
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
//这个搞不懂
LiveBeansView.registerApplicationContext(this);
}
/*
初始化lifecycleProcessor
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//是否包含lifecycleProcessor
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
//初始化默认lifecycleProcessor
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
/*
装饰事件
广播指定事件给指定监听器
推送事件到parent context
*/
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary
//如有必要,将事件装饰为ApplicationEvent
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
// Multicast right now if possible - or lazily once the multicaster is initialized
//如果可能的话,现在就进行多播-或者在初始化多播主机后进行惰性的多播
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
//自定义的事件,广播到指定类型上
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// Publish event via parent context as well...
//推送事件到parent context
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
//通知所有注册的监听器
this.parent.publishEvent(event);
}
}
}