Spring源码9. refreshContext()刷新应用
上篇回顾
上一篇prepareContext()准备应用上下文中分析了spring容器的准备, 共计执行了如下8步:
- 统一了ApplicationContext和Application的environment
- 设置ApplicationContext的beanNameGenerator,resouceLoader和classLoader, 并设置beanFactory的类型转换Service
- 执行Initializer
- 发布ApplicationContextInitializedEvent
- 打印启动日志和profile日志
- 手工注册命令行和banner两个单例Bean
- 初始化BeanDefinitionLoader, 加载启动类sources
- 发布contextLoaded事件
目录
1. 刷新应用上下文
2. AbstractApplicationContext#refresh
3. 准备刷新 prepareRefresh()
3.1 AnnotationConfigServletWebServerApplicationContext
3.2 AbstractApplicationContext
4. 获取并刷新beanFactory
5. 准备beanFactory
6. beanFactory的后置处理器
7. 实现beanFactory的后置处理器
8.注册bean处理器
9.国际化 initMessageSource()
10. 注册事件发布器
11. 通知子类刷新刷新容器 onRefresh()
ServletWebServerApplicationContext
GenericWebApplicationContext
12.注册监听器 registerListeners()
13. 完成beanFactory初始化, 实例化所有非延迟加载的bean
14.完成刷新 finishRefresh() 发布ContextRefreshedEvent
15. 异常处理
16. 清除缓存 resetCommonCaches()
1. 刷新应用上下文
public class SpringApplication {
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//本文的重点
//刷新应用上下文
refreshContext(context);
//...
}
//刷新应用上下文,注册关闭应用钩子
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
//registerShutdownHook默认为true
try {
//注册shutdown方法
context.registerShutdownHook();
}
catch (AccessControlException ex) { }
}
}
//刷新应用上下文
//调用AbstractApplicationContext#refresh方法
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
}
2. AbstractApplicationContext#refresh
/**
* 抽象父类ApplicationContext
*/
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//准备刷新
prepareRefresh();
//刷新beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//准备beanFactory
prepareBeanFactory(beanFactory);
try {
//beanFactory的后置处理器
postProcessBeanFactory(beanFactory);
//实现beanFactory的后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
//beanFactory注册后置处理器
registerBeanPostProcessors(beanFactory);
//初始化messageSource
initMessageSource();
//初始化Application事件发布器
initApplicationEventMulticaster();
//初始化其他特殊的bean
onRefresh();
//注册监听器
registerListeners();
//完成beanFactory初始化
finishBeanFactoryInitialization(beanFactory);
//完成刷新,发布完成事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
//打印告警日志
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
//捕获到异常,销毁已经注册的bean
destroyBeans();
//捕获到异常,取消刷新
cancelRefresh(ex);
//抛出异常
throw ex;
}
finally {
//重置缓存
resetCommonCaches();
}
}
}
}
3. 准备刷新 prepareRefresh()
准备刷新, 执行了两步:
- 调用当前类AnnotationConfigServletWebServerApplicationContext的prepareRefresh()方法
- 显式调用super.prepareRefresh()方法,也就是AbstractApplicationContext的prepareRefresh方法
3.1 AnnotationConfigServletWebServerApplicationContext#prepareRefresh
清空CachingMetadataReaderFactory中的缓存
public class AnnotationConfigServletWebServerApplicationContext
extends ServletWebServerApplicationContext implements AnnotationConfigRegistry {
//准备刷新
@Override
protected void prepareRefresh() {
//如果类扫描器中的metadataReaderFactoryy是CachingMetadataReaderFactory的子类
//那么清除类扫描器中beanFactory维护的所有的bean
this.scanner.clearCache();
//显式调用父类AbstractApplicationContext的prepareRefresh方法
super.prepareRefresh();
}
}
3.2 AbstractApplicationContext#prepareRefresh
设置刷新开始事件, 设置closed为false, active为true, 标记容器处于active状态
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
//准备刷新
protected void prepareRefresh() {
//记录开始时间,调整active状态
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
//打印debug日志
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
//初始化占位符,例如:$,#,{}
//GenericWebApplicationContext#initPropertySources
initPropertySources();
//当前environment为StandardServletEnvironment
//调用AbstractEnvironment#validateRequiredProperties()方法
//然后调用AbstractPropertyResolver#validateRequiredProperties()方法
//如果属性中缺少requiredProperties
//那么抛出MissingRequiredPropertiesException
getEnvironment().validateRequiredProperties();
if (this.earlyApplicationListeners == null) {
//如果earlyApplicationListeners为null
//保存applicationListeners
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
//如果earlyApplicationListeners不为null
//将earlyApplicationListeners同步到applicationListeners中
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
//初始化earlyApplicationEvents
this.earlyApplicationEvents = new LinkedHashSet<>();
}
}
4. 获取并刷新beanFactory
AbstractApplicationContext中定义了模板方法, refreshBeanFactory和getBeanFactory调用的是GenericApplicationContext中实现的方法
public abstract class AbstractApplicationContext extends DefaultResourceLoader{
//id获取
private String id = ObjectUtils.identityToString(this);
//刷新并返回beanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
@Override
public String getId() {
return this.id;
}
}
GenericApplicationContext#refreshBeanFactory
更新this.refreshed字段为true, 表示已经更新了, 然后beanFactory设置serializationId, 最后返回beanFactory
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
//内部的beanFactory
private final DefaultListableBeanFactory beanFactory;
//原子bool值
private final AtomicBoolean refreshed = new AtomicBoolean();
//刷新beanFactory
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
//原子自旋, 更新refreshed为true
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
//调用AbstractApplicationContext的getId()方法
this.beanFactory.setSerializationId(getId());
}
//返回beanFactory
@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
}
5. 准备beanFactory
beanFactory是GenericApplicationContext中DefaultListableBeanFactory类型的成员变量, 设置beanFactory, 一共执行了
- 配置classLoader为当前context的classLoader
- 设置BeanExpressionResolver, 解析EL表达式
- 设置属性编辑器
- 添加BeanPostProcessor
- 配置自动装配
- 手工注册environment相关bean
public abstract class AbstractApplicationContext extends DefaultResourceLoader{
protected void prepareBeanFactory()(ConfigurableListableBeanFactory beanFactory) {
//beanFactory设置为当前context的classLoader
beanFactory.setBeanClassLoader(getClassLoader());
//beanFactory设置BeanExpressionResolver,解析EL表达式
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//beanFactory配置属性编辑器,也就是类型转换器
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
//ApplicationContextAwareProcessor会在加载Aware接口的时候, 传递参数到相应的Aware实现类中
//所以需要忽略Aware接口的自动装配
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//配置忽略自动装配
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 配置自动装配规则, 例如@Autowired注解注入
// 如果需要BeanFactory,那么注入beanFactory
// 如果需要ResourceLoader,ApplicationEventPublisher,ApplicationContext,则注入this
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
//添加ApplicationListenerDetector的beanPostProcessor
//ApplicationListenerDetector会检测实现了ApplicationListener接口的bean
//在这些bean在实例化的过程中,记录到singletonNames 中
//在bean被销毁的时候, 从applicationContext的applicationEventMulticaster中移除
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
//添加LoadTimeWeaverAwareProcessor
//解析@EnableLoadTimeWeaving注解
//在类加载到JVM中时, 织入切面
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
//添加bean处理器,实现对AspectJ的支持
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
//设置classloader
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 手工注册environment的相关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());
}
}
}
6. beanFactory的后置处理器 postProcessBeanFactory(beanFactory)
后续处理各个beanFactory, 当前applicationContext是AnnotationConfigServletWebServerApplicationContext的实例, postProcessBeanFactory执行了三步
- 调用了父类方法
- 判断basePackages是否为空, 不为空的话, 扫描this.basePackages
- 判断annotatedClasses是否为空, 不为空的话, 注册bean
AnnotationConfigServletWebServerApplicationContext#postProcessBeanFactory
public class AnnotationConfigServletWebServerApplicationContext
extends ServletWebServerApplicationContext implements AnnotationConfigRegistry {
//处理beanFactory
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//显式调用父类ServletWebServerApplicationContext#postProcessBeanFactory
super.postProcessBeanFactory(beanFactory);
//basePackages默认为null
if (this.basePackages != null && this.basePackages.length > 0) {
//不为空的话,进行扫描
this.scanner.scan(this.basePackages);
}
//annotatedClasses默认为空
if (!this.annotatedClasses.isEmpty()) {
//不为空的话注册类
this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
}
}
}
ServletWebServerApplicationContext#postProcessBeanFactory
进行了两个操作, 首先添加了一个WebApplicationContextServletContextAwareProcessor的Aware Bean处理器, ServletContextAware的子类Bean在实例化过程中, 会被注入servletContext和servletConfig对象, 然后beanFactory中注册了request和session两个scopes, 注册了几个Autowired依赖类
public class ServletWebServerApplicationContext extends GenericWebApplicationContext
implements ConfigurableWebServerApplicationContext {
@Override
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//在ServletContext和ServletConfig初始化之前
//进行bean处理
beanFactory.addBeanPostProcessor(
new WebApplicationContextServletContextAwareProcessor(this));
//忽略ServletContextAware自动配置
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
//beanFactory注册web应用scopes
//request和session
registerWebApplicationScopes();
}
}
WebApplicationContextUtils#registerWebApplicationScopes
注册了request, session两个scope, 然后注册ServletRequest, ServletResponse, HttpSession, WebRequest
public abstract class WebApplicationContextUtils# {
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory) {
//传入ServletContext为null
registerWebApplicationScopes(beanFactory, null);
}
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
@Nullable ServletContext sc) {
//注册Scope
//request
beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
//session
beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
if (sc != null) {
//传入sc为null
//注册application scope
ServletContextScope appScope = new ServletContextScope(sc);
beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
// 设置ServletContext属性
sc.setAttribute(ServletContextScope.class.getName(), appScope);
}
//注册几个Autowired自动装配
//ServletRequest.class
beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
//ServletResponse.class
beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
//HttpSession.class
beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
//WebRequest.class
beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
if (jsfPresent) {
//jsfPresent默认为false
FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
}
}
}
7. 实现beanFactory的后置处理器
BeanFactoryPostProcessor是一个接口, 处理beanFactory中所有的bean, 在所有的beanDefinition加载完成之后, BeanFactoryPostProcessor可以对beanDefinition进行属性的修改, 之后再进行bean实例化
BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口, 定义了postProcessBeanDefinitionRegistry方法, 会在postProcessBeanFactory方法执行之前, 获取bean定义, 并注册到spring容器中
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//处理器代理类
//处理this.beanFactoryPostProcessors中维护的bean处理器
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
//TempClassLoader为空
//包含了LoadTimeWeaver(加载到JVM时, 进行切面织入)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
7.1 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()
如果beanFactory是BeanDefinitionRegistry的子类, 按优先级处理BeanDefinitionRegistryPostProcessor类型的后置处理器, 最后处理传入的其他类型后置处理器, 处理流程如下:
首先处理传入的beanFactoryPostProcessors, 将传入的beanFactoryPostProcessors分为两个部分
- BeanDefinitionRegistryPostProcessor子类, 执行其postProcessBeanDefinitionRegistry方法, 然后维护到registryProcessors的列表中
- 非BeanDefinitionRegistryPostProcessor子类, 维护到regularPostProcessors列表中
然后处理beanFactory中注册的BeanDefinitionRegistryPostProcessor类型的bean
- 优先处理实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor, 一共分为5个步骤
- 生成bean, 维护到currentRegistryProcessors列表中
- processedBeans中添加bean名称, 标记已经被处理
- currentRegistryProcessors列表排序, 并添加到registryProcessors中
- 遍历registryProcessors列表, 调用每个元素的postProcessBeanDefinitionRegistry方法
- 然后清空currentRegistryProcessors
- 然后处理实现了Ordered接口的BeanDefinitionRegistryPostProcessor, 一共分为5个步骤
- 先判断processedBeans中是否包含了beanName, 如果包含了就不处理
- 生成bean, 维护到currentRegistryProcessors列表中
- processedBeans中添加bean名称, 标记已经被处理
- currentRegistryProcessors列表排序, 并添加到registryProcessors中
- 遍历registryProcessors列表, 调用每个元素的postProcessBeanDefinitionRegistry方法
- 然后清空currentRegistryProcessors
- 处理剩下的所有BeanDefinitionRegistryPostProcessor, 方法同第2步
- 遍历registryProcessors, 调用其postProcessBeanFactory方法
- 遍历所有的regularPostProcessors, 调用其postProcessBeanFactory方法
如果beanFactory不是BeanDefinitionRegistry的子类, 那么直接遍历传入的传入的beanFactoryPostProcessors, 调用元素的postProcessBeanFactory方法
最后处理beanFactory中注册的其他类型的BeanFactoryPostProcessor, 获取bean名称, 维护到postProcessorNames列表中, 之后的处理步骤如下:
- 首先处理实现了PriorityOrdered接口的BeanFactoryPostProcessor
- 获取bean, 维护到priorityOrderedPostProcessors列表中
- priorityOrderedPostProcessors排序
- 遍历priorityOrderedPostProcessors, 执行其postProcessBeanFactory方法
- 然后处理实现了Ordered接口的BeanFactoryPostProcessor, 方法同上
- 最后处理其他BeanFactoryPostProcessor, 方法同上
ConfigurationClassPostProcessor处理了@Configuration注解, 扫描项目中的BeanDefinition, 这篇文章 详细剖析了ConfigurationClassPostProcessor的源码
final class PostProcessorRegistrationDelegate {
/**
* @param beanFactory
* @param beanFactoryPostProcessors有三个:
* CachingMetadataReaderFactoryPostProcessor
* ConfigurationWarningsPostProcessor
* PropertySourceOrderingPostProcessor
*/
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
//processedBeans记录处理过的bean名称
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
//优先处理传入的BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//非BeanDefinitionRegistryPostProcessor类型, 常规BeanFactory后置处理器
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
//BeanDefinitionRegistryPostProcessor类型的bean定义注册器后置处理器
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//regularPostProcessors有1个:PropertySourceOrderingPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
//bean定义注册器后置处理器,有如下两个:
//CachingMetadataReaderFactoryPostProcessor
//ConfigurationWarningsPostProcessor
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
//执行其postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
//然后加入到registryProcessors中
registryProcessors.add(registryProcessor);
}
else {
//如果不是BeanDefinitionRegistryPostProcessor
//那么放入regularPostProcessors(常规后置处理器)中
regularPostProcessors.add(postProcessor);
}
}
//处理beanFactory中注册的BeanDefinitionRegistryPostProcessor
//当前正在处理的PostProcessor, 处理完成之后会清空
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
//将其名称放入postProcessorNames数组中
//当前只能获取到一个bean:
//名称为org.springframework.context.annotation.internalConfigurationAnnotationProcessor
//类型为ConfigurationClassPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
//优先处理PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
//处理完成之后, 放到processedBeans列表
processedBeans列表中.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
//添加到registryProcessors
registryProcessors.addAll(currentRegistryProcessors);
//遍历currentRegistryProcessors,调用其postProcessBeanDefinitionRegistry方法
//执行ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry, 扫描并注册模块中@Configuration注解的bean
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
//清空currentRegistryProcessors
currentRegistryProcessors.clear();
// 实现Order注解的bean
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();
// 最后,调用其他的BeanDefinitionRegistryPostProcessor的方法
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();
}
//调用BeanDefinitionRegistryPostProcessor的postProcessBeanFactory
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//方法传入普通BeanFactoryPostProcessor, 实现其postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
//如果beanFactory不是BeanDefinitionRegistry
//方法传入普通BeanFactoryPostProcessor, 实现其postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
//处理beanFactory中注册的普通BeanFactoryPostProcessor
//非BeanDefinitionRegistryPostProcessor类型后置处理器
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
//说明已经处理过了
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
//优先处理实现了PriorityOrdered接口的子类
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
//再处理实现了Ordered接口的子类
orderedPostProcessorNames.add(ppName);
}
else {
//最后处理其他BeanFactoryPostProcessor
nonOrderedPostProcessorNames.add(ppName);
}
}
//实现了PriorityOrdered接口的BeanFactoryPostProcessor, 优先处理
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 实现了Ordered接口的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 最后再实现不排序BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// 清除缓存
beanFactory.clearMetadataCache();
}
}
8.注册bean处理器 registerBeanPostProcessors(beanFactory)
BeanPostProcessor是一个接口, Bean后置处理器, 在bean实例化, 之前执行postProcessBeforeInitialization方法, 在bean实例化之后执行postProcessAfterInitialization方法, 实现了对bean实例的增强
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
//注册beanPostProcessors
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
}
PostProcessorRegistrationDelegate.registerBeanPostProcessors
beanFactory中获取BeanPostProcessor类型的bean名称, 维护到postProcessorNames数组中, 将BeanPostProcessor列表分为四类:
- 实现了PriorityOrdered接口, 维护到priorityOrderedPostProcessors列表中
- 实现了Ordered接口的BeanPostProcessor, 维护到orderedPostProcessorNames列表中
- 没有实现排序接口的, 维护到nonOrderedPostProcessorNames列表中
- 实现了MergedBeanDefinitionPostProcessor接口, 维护到internalPostProcessors列表中
beanFactory先添加一个BeanPostProcessorChecker类型的BeanPostProcessor, 然后在将各类PostProcessors列表排序, 分别添加到beanFactory的beanPostProcessor列表中, 最后再添加一个ApplicationListenerDetector
final class PostProcessorRegistrationDelegate {
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 添加一个BeanPostProcessorChecker
// beanFactory数量不符合时,会打印info日志
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// BeanPostProcess分类
// 实现了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)) {
//PriorityOrdered子类
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
//MergedBeanDefinitionPostProcessor子类
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// Ordered子类
orderedPostProcessorNames.add(ppName);
}
else {
// 普通BeanPostProcessor
nonOrderedPostProcessorNames.add(ppName);
}
}
// 实现了PriorityOrdered接口的BeanPostProcessor, 先排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 然后添加到beanFactory中
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 实现了Ordered接口的BeanPostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
// 先从beanFactory中获取bean
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
// 然后添加到orderedPostProcessors列表中
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
// 如果是MergedBeanDefinitionPostProcessor的子类
// 那么加入internalPostProcessors中
internalPostProcessors.add(pp);
}
}
// 排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 添加到beanFactory中
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 添加其他BeanPostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
// 如果是MergedBeanDefinitionPostProcessor的子类
// 那么加入internalPostProcessors中
internalPostProcessors.add(pp);
}
}
// 添加到beanFactory中
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 最后internalPostProcessors排序
// 添加到beanFactory中
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 添加一个ApplicationListenerDetector的beanFactory
// 处理ApplicationListener类型的bean
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
}
9.国际化 initMessageSource()
先判断容器beanFactory中是否包含messageSource bean定义, 存在的话, 直接获取bean, 如果不存在的话, 那么手工注册一个messageSource单例bean, 然后赋值给this.messageSource
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//判断容器中是否包含messageSource bean定义
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
//容器中存在bean定义, 那么直接获取bean
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
//HierarchicalMessageSource可以实现消息的嵌套
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
//容器中没有messageSource bean定义
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
//手工注册一个单例messageSource bean
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
10. 注册事件发布器 initApplicationEventMulticaster()
先判断容器beanFactory中是否有applicationEventMulticaster bean定义, 存在的话, 获取bean实例, 不存在的话, 实例化一个SimpleApplicationEventMulticaster, 手工注册一个单例bean, 然后赋值给this.applicationEventMulticaster
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//先判断容器beanFactory中是否有applicationEventMulticaster bean定义
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
//存在的话, 获取bean实例
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
//容器中不存在的话, 实例化一个SimpleApplicationEventMulticaster
//手工注册一个单例bean
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() + "]");
}
}
}
11. 通知子类刷新刷新容器 onRefresh()
AbstractApplicationContext没有实现该方法, 用于通知子类刷新容器
ServletWebServerApplicationContext
调用父类GenericWebApplicationContext#onRefresh方法, 然后创建webServer, 之后调用父类GenericWebApplicationContext#initPropertySources方法, 将servletContext维护到environment的servletContextInitParams属性中
public class ServletWebServerApplicationContext extends GenericWebApplicationContext
implements ConfigurableWebServerApplicationContext {
@Override
protected void onRefresh() {
//调用父类onRefresh方法
super.onRefresh();
try {
//创建webServer
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
//创建webServer
private void createWebServer() {
WebServer webServer = this.webServer;
//默认servletContext为null
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
//获取一个ServletWebServerFactory
ServletWebServerFactory factory = getWebServerFactory();
//factory获取一个webServer
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
//servletContext不为空
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context",
ex);
}
}
//初始化
initPropertySources();
}
}
GenericWebApplicationContext
初始化主题, 可以让页面显示不同的样式
public class GenericWebApplicationContext extends GenericApplicationContext
implements ConfigurableWebApplicationContext, ThemeSource {
@Override
protected void onRefresh() {
//初始化资源
this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}
}
12.注册监听器 registerListeners()
首先将硬编码的ApplicationListener先添加this.applicationEventMulticaster.defaultRetriever.applicationListeners中, 然后将注入的listener bean维护到this.applicationEventMulticaster.defaultRetriever.applicationListenerBeans, 最后处理earlyEvent
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
protected void registerListeners() {
// 首先将硬编码的ApplicationListener先添加applicationEventMulticaster中
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 然后将注入的listener bean维护到applicationEventMulticaster中
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 处理earlyEvent
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
}
13. 完成beanFactory初始化, 实例化所有非延迟加载的bean
beanFactory.preInstantiateSingletons() 源码剖析
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化ConversionService的实例化
// 然后赋值给beanFactory.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));
}
// 如果beanFactory中没有@Value解析器
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 类加载期间织入的切面
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
//实例化所有LoadTimeWeaverAware类型的bean
getBean(weaverAwareName);
}
//停止使用临时ClassLoader
beanFactory.setTempClassLoader(null);
//冻结配置,不再允许改变
beanFactory.freezeConfiguration();
//实例化所有非延迟加载的bean
beanFactory.preInstantiateSingletons();
}
}
14.完成刷新 finishRefresh()
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
protected void finishRefresh() {
// 清空缓存
clearResourceCaches();
// 初始化一个LifecycleProcessor
// 在Spring启动的时候启动bean
// 在spring结束的时候销毁bean
initLifecycleProcessor();
// 调用LifecycleProcessor的onRefresh方法
// 启动实现了Lifecycle接口的bean
getLifecycleProcessor().onRefresh();
// 发布ContextRefreshedEvent
publishEvent(new ContextRefreshedEvent(this));
// 如果配置了"spring.liveBeansView.mbeanDomain"的系统属性,制定了MBeanServer,
// 那么会将ApplicationContext注册到MBeanServer中,
// 可以通过MBeanServer,对spring容器中的bean,进行实时的查看和管理
LiveBeansView.registerApplicationContext(this);
}
}
发布ContextRefreshedEvent
DelegatingApplicationListener
什么都没有做
ConditionEvaluationReportListener
打印@Condition注解评估日志
public class ConditionEvaluationReportLoggingListener
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
protected void onApplicationEvent(ApplicationEvent event) {
ConfigurableApplicationContext initializerApplicationContext = this.applicationContext;
if (event instanceof ContextRefreshedEvent) {
//打印刷新成功日志
if (((ApplicationContextEvent) event)
.getApplicationContext() == initializerApplicationContext) {
logAutoConfigurationReport();
}
}
else if (event instanceof ApplicationFailedEvent
&& ((ApplicationFailedEvent) event)
.getApplicationContext() == initializerApplicationContext) {
//打印失败日志
logAutoConfigurationReport(true);
}
}
}
ClearCachesApplicationListener
清空ReflectionUtils的缓存, 递归清空classLoader缓存
class ClearCachesApplicationListener
implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ReflectionUtils.clearCache();
clearClassLoaderCaches(Thread.currentThread().getContextClassLoader());
}
}
SharedMetadataReaderFactoryBean
static class SharedMetadataReaderFactoryBean
implements FactoryBean<ConcurrentReferenceCachingMetadataReaderFactory>,
BeanClassLoaderAware, ApplicationListener<ContextRefreshedEvent> {
public void onApplicationEvent(ContextRefreshedEvent event) {
//清空metadataReaderFactory的缓存
this.metadataReaderFactory.clearCache();
}
}
ResourceUrlProvider
public class ResourceUrlProvider implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//默认为true
if (isAutodetect()) {
//自动推断pattern对应的ResourceHttpRequestHandler
this.handlerMap.clear();
detectResourceHandlers(event.getApplicationContext());
if (!this.handlerMap.isEmpty()) {
this.autodetect = false;
}
}
}
}
15. 异常处理
//beanFactory销毁注册的bean
destroyBeans();
//ApplicationContext取消刷新
cancelRefresh(ex);
16. 清除缓存 resetCommonCaches()
protected void resetCommonCaches() {
//反射工具类的缓存清空
ReflectionUtils.clearCache();
//注解工具类的缓存清空
AnnotationUtils.clearCache();
//ResolvableType的缓存清空
ResolvableType.clearCache();
//清空ClassLoader
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
总结
本文主要分析了spring容器的刷新, 首先更新刷新状态, 然后处理beanFactory的后置处理器, 用于注册bean定义, 其中ConfigurationClassPostProcessor处理器, 处理模块中@Configuration注解, onRefresh()方法中, 实例化了TomcatWebServer, 最后在finishRefresh()中, 实例化了所有bean
下一篇
我们将会在下一篇启动完成, 研究springboot启动完成的操作