spring 启动过程解析(二)
spring 容器刷新,bean对象初始化前过程解析
spring 过程中核心功能,通过调用refresh()方法来加载或刷新持久化的配置,并且进行bean的注册功能。
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
public void refresh() throws BeansException, IllegalStateException {
// synchronized修饰,线程安全
synchronized(this.startupShutdownMonitor) {
// 刷新前容器准备工作
this.prepareRefresh();
// 判断容器是否能够刷新
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
// beanfactory准备工作
this.prepareBeanFactory(beanFactory);
try {
// 为子类提供自定义处理beanfactory方法,一般用于子类自定实现
this.postProcessBeanFactory(beanFactory);
// 执行BeanFactoryPostProcessor,开始对BeanFactory进行处理
this.invokeBeanFactoryPostProcessors(beanFactory);
// 注册beanPostProcessor
this.registerBeanPostProcessors(beanFactory);
//国际化处理
this.initMessageSource();
// 初始化时间广播
this.initApplicationEventMulticaster();
// 自定义实现某些bean
this.onRefresh();
// 注册ApplicationListener
this.registerListeners();
// 初始化其他bean对象
this.finishBeanFactoryInitialization(beanFactory);
// 完成刷新
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
...
}
1.prepareRefresh()
prepareRefresh主要是在刷新前容器准备工作,包括:
- 设置启动时间
- 判断日志打印级别,进行日志打印
- 初始配置参数
- 初始化监听队列
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
...
protected void prepareRefresh() {
// 设置启动时间
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (this.logger.isDebugEnabled()) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Refreshing " + this);
} else {
this.logger.debug("Refreshing " + this.getDisplayName());
}
}
// 初始化PropertySources,子类可自定义实现,允许子类设置一些内容到Environment中
this.initPropertySources();
// 验证Environment中是否包括了必须要有的属性
this.getEnvironment().validateRequiredProperties();
// 初始化前期监听队列
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
} else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
this.earlyApplicationEvents = new LinkedHashSet();
}
...
}
2.obtainFreshBeanFactory()
obtainFreshBeanFactory主要是用于判断容器是否能够刷新,若能刷新,返回容器的beanFactory(默认是ConfigurableListableBeanFactory)
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
...
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 一般情况调用子类的实现的refreshBeanFactory来判断是否能够进行刷新
this.refreshBeanFactory();
return this.getBeanFactory();
}
...
}
3.prepareBeanFactory(beanFactory)
beanfactory准备工作,具体包括:
- 设置BeanFactory的类加载器
- 增加一个ResourceEditorRegistrar,注册一些级别的类型转化器
- 增加一个ApplicationContextAwareProcessor,,用来处理ignoreDependencyInterface方法忽略的接口,处理EnvironmentAware、EmbeddedValueResolverAware等相关回调
- 忽略指定依赖,相关Aware类型的bean忽略依赖注入,包括:EnvironmentAware,EmbeddedValueResolverAware,ApplicationEventPublisherAware,ApplicationEventPublisherAware,ApplicationContextAware
- 添加ApplicationListenerDetector,把ApplicantsListener类型的Bean注册到ApplicationContext中
- 添加LoadTimeWeaverAwareProcessor,设置临时类的类加载器(用于面向切面编程)
- 注册默认bean,包括environment,systemProperties,systemEnvironment,applicationStartup
- 注意:设置bean el表达式解析器 Spring5.3中新增的功能,可以选择是否开启Springel功能,shouldIgnoreSpringel默认为false,表示开启
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
...
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
//beanFactory设置bean对象的类型加载器
beanFactory.setBeanClassLoader(this.getClassLoader());
// beanFactory设置bean表达式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// beanFactory增加ResourceEditorRegistrar
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, this.getEnvironment()));
// 增加ApplicationContextAwareProcessor
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);
// 注册spring默认对象
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// 添加ApplicationListenerDetector,用于处理把ApplicantsListener类型的Bean注册到ApplicationContext中,统一监听
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// 判断当前beanfactory是否已经包含loadTimeWeaver
if (beanFactory.containsBean("loadTimeWeaver")) {
// 添加LoadTimeWeaverAwareProcessor
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// 设置当前beanfactory的加载器为临时类的类加载器(用于面向切面编程对象加载)
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// 注册默认bean
if (!beanFactory.containsLocalBean("environment")) {
beanFactory.registerSingleton("environment", this.getEnvironment());
}
if (!beanFactory.containsLocalBean("systemProperties")) {
beanFactory.registerSingleton("systemProperties", this.getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean("systemEnvironment")) {
beanFactory.registerSingleton("systemEnvironment", this.getEnvironment().getSystemEnvironment());
}
}
...
}
4.invokeBeanFactoryPostProcessors(beanFctory)
invokeBeanFactoryPostProcessors 主要是对beanFactory进行后置处理,默认情况下,会
- 执行手动添加的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法
- 执行扫描出来的BeanDefinitionRegistryPostProcessor(实现了PriorityOrdered)的postProcessBeanDefinitionRegistry()方法
- 执行扫描出来的BeanDefinitionRegistryPostProcessor(实现了Ordered的postProcessBeanDefinitionRegistry()方法
- 执行扫描出来的BeanDefinitionRegistryPostProcessor(普通) 的postProcessBeanDefinitionRegistry()方法
- 执行扫描出来的BeanDefinitionRegistryPostProcessor(所有) 的postProcessBeanFactory()方法
- 执行手动添加的BeanFactoryPostProcessor的postProcessBeanFactory()方法
- 执行扫描出来的BeanFactoryPostProcessor(实现了PriorityOrdered)的postProcessBeanFactory()方法
- 执行扫描出来的BeanFactoryPostProcessor(实现了Ordered) 的postProcessBeanFactory()方法
- 执行扫描出来的BeanFactoryPostProcessor(普通)的postProcessBeanFactory()方法
核心代码
final class PostProcessorRegistrationDelegate {
...
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
Set<String> processedBeans = new HashSet<>();
// 判断 beanFactory factory的类型是否是BeanDefinitionRegistry及其子类
if (beanFactory instanceof BeanDefinitionRegistry) {
// 强制类型转换
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 新建 BeanFactoryPostProcessor 列表对象
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 新建 BeanDefinitionRegistryPostProcessor 列表对象
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 对BeanFactoryPostProcessor进行分类
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 判断是否是BeanDefinitionRegistryPostProcessor 接口的实现类
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 执行预注册
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// 根据类型获取beanfactory中包含BeanDefinitionRegistryPostProcessor属性的实例
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 处理 BeanDefinitionRegistryPostProcessors中实现了 PriorityOrdered类
for (String ppName : postProcessorNames) {
// for 循环判断,是否实现了PriorityOrdered
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 添加对应实例到列表中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 实例名称添加到 记录中
processedBeans.add(ppName);
}
}
// 升序排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// beanfactory实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor添加到集合中
registryProcessors.addAll(currentRegistryProcessors);
// 循环调用Processor的postProcessBeanDefinitionRegistry方法的,执行相关BeanDefinition处理
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 处理 BeanDefinitionRegistryPostProcessors中实现了Ordered类,具体处理逻辑与PriorityOrdered相似
for (String ppName : postProcessorNames) {
// processedBeans表示该beanFactoryPostProcessor的postProcessBeanDefinitionRegistry()方法已经执行过了,不再重复执行
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
boolean reiterate = true;
//执行没有实现了PriorityOrdered或Ordered接口其他processor
while (reiterate) { // while ? 在该过程中可能会有另外的BeanDefinitionRegistryPostProcessor注册到beanFctory中,通过while确保所有的BeanDefinitionRegistryPostProcessor都执行完成
// 例如A注册了B和C,B又注册了D和E,那么B和C会按顺序执行,D和E也会按顺序执行,但是B、C、D、E整体不能保证是顺序执行
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, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
}
// 执行完BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()方法后, 统一再执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessors)
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 执行手动添加的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, 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)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
beanFactory.clearMetadataCache();
}
...
}
注意
- ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(registry): 解析配置类,包括@Configuration,@Component、@ComponentScan、@Import、@ImportResource、@Bean等
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
// 解析配置类
processConfigBeanDefinitions(registry);
}
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
// 检查当前类是否是包含@Configuration,@Component、@ComponentScan、@Import、@ImportResource注解
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
if (configCandidates.isEmpty()) {
return;
}
// 升序排序,@Order越小越靠前
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// 单实例注册器
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
// 先往单例池中添加一个org.springframework.context.annotation.internalConfigurationBeanNameGenerator的BeanNameGenerator类型的bean,用来作为扫描得到的Bean和import导入进来的Bean的beanName
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// 设置@Configration解析类
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
// 递归解析配置类
do {
StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
// 解析配置类
parser.parse(candidates);
parser.validate();
// 之后的结果
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// 当BeanDefinitionReader不存在时设置BeanDefinitionReader
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 蒋所有的Configuration类型加载成BeanDefinition,一般一个配置类会对应一个BeanDefinition,单当右@Bean或@ImportResource存在时,会有多个BeanDefinition
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();
candidates.clear();
// 判断beanDefinition总量是否增加,若有,需要处理新增的配置类
if (registry.getBeanDefinitionCount() > candidateNames.length) {
// 获取所有beanDefinition
String[] newCandidateNames = registry.getBeanDefinitionNames();
// 获取原有配置类
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
// 检查多出来的BeanDefinition是不是配置类,需不需要解析
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
- EventListenerMethodProcessor.postProcessBeanFactory():事件监听方法后置处理器
查询所有继承子EventListenerFactory中的bean
排序后添加到事件监听工厂中
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
// 类型获取EventListenerFactory相关实现类
Map<String, EventListenerFactory> beans = beanFactory.getBeansOfType(EventListenerFactory.class, false, false);
// 获取相关值
List<EventListenerFactory> factories = new ArrayList(beans.values());
// 排序操作
AnnotationAwareOrderComparator.sort(factories);
this.eventListenerFactories = factories;
}
5.registerBeanPostProcessors()
registerBeanPostProcessors将扫描到的BeanPostProcessors实例化并排序,添加到BeanFactory的beanPostProcessors属性,具体步骤如下:
- 执行实现PriorityOrdered的PostProccssor实例化
- 执行实现Oder的PostProcessor实例化
- 执行其他PostProcessor实例化
- 最后再执行实现了MergedBeanDefinitionPostProcessor的Proceessor(添加到beanPostProcessors时,若有重复的,先删除,再追加)
- ApplicationListenerDetector放在所有BeanPostProcessor之后
ApplicationListenerDetector用于监听listnener
final class PostProcessorRegistrationDelegate {
...
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 根据类型获取beanFactory中的BeanPostProcessor
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// beanProcessorTargetCount表示BeanFactory中所有的BeanPostProcessor数量
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
// +1表示BeanPostProcessorChecker
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 将BeanPostProcessor分类
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 执行实现PriorityOrdered的PostProccssor并先实例化
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
// 判断对象是否实现MergedBeanDefinitionPostProcessor,是的话进行后续处理
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// 添加Order的PostProcessor bean
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
//添加其他PostProcessor
nonOrderedPostProcessorNames.add(ppName);
}
}
// 升序排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 将priorityOrderedPostProcessors添加到beanFactory.beanPostProcessorsz中
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 实例化包含添加Order的PostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
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);
// 实例化其他的PostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
sortPostProcessors(internalPostProcessors, beanFactory);
// 将实现MergedBeanDefinitionPostProcessor的processor重新注册(添加到beanPostProcessors时,若有重复的,先删除,再追加))
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 最后添加ApplicationListenerDetector
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
// Nothing to sort?
if (postProcessors.size() <= 1) {
return;
}
Comparator<Object> comparatorToUse = null;
if (beanFactory instanceof DefaultListableBeanFactory) {
comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
}
if (comparatorToUse == null) {
comparatorToUse = OrderComparator.INSTANCE;
}
postProcessors.sort(comparatorToUse);
}
...
}
6.initMessageSource()
设置ApplicationContext的MessageSource,用户自定义,默认为DelegatingMessageSource,国际化设置
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
...
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断是否存在名称为messageSource的beanfactory
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 获取bean对象
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// 判断父类上下文是否存在
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// 使用父ApplicationContext的messageSource作为this.messageSource的父messageSource
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// 初始化默认国际化信息,默认为DelegatingMessageSource
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
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 + "]");
}
}
}
...
}
7.initApplicationEventMulticaster()
设置ApplicationContext的applicationEventMulticaster,可自定义,默认为SimpleApplicationEventMulticaster
初始化应用事件广播器,。观察者模式的应用。当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
...
protected void initApplicationEventMulticaster() {
// 获取当前beanfactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断是存在名称为applicationEventMulticaster的bean
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 {
// 新建SimpleApplicationEventMulticaster
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() + "]");
}
}
}
//
}
8.onRefresh()
给子类的模板方法,是模板方法,具体的子类可以在这里初始化一些特殊的Bean(在初始化 singleton beans 之前)
9.registerListeners()
定义的ApplicationListener的Bean对象,设置到ApplicationContext中去,并执行在此之前所发布的事件
ApplicationListener 添加到 ApplocationEventMultcaster中
protected void registerListeners() {
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
// 将已经注册的applicationListeners添加到广播监听器中
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 根据类型获取ApplicationListener监听类bean,并逐一添加到事件广播器中
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 判断是否有earlyApplicationEvents,如果有就使用事件广播器发布earlyApplicationEvents
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
}