Spring源码解析 – AnnotationConfigApplicationContext容器创建过程
Spirng在BeanFactory基础上提供了一些具体容器的实现,其中AnnotationConfigApplicationContext是一个用来管理注解bean的容器,从AnnotationConfigApplicationContext的实现结构中可以看出:
AnnotationConfigApplicationContext继承GenericApplicationContext这个通用应用上下文,并且在GenericApplicationContext内部定义了一个DefaultListableBeanFactory实例。
GenericApplicationContext实现了BeanDefinitionRegistry接口,所以可以通过AnnotationConfigApplicationContext实例注册beandefintion,然后调用refresh()方法来初始化上下文。
AnnotationConfigApplicationContext继承了
AbstractApplicationContext,AbstractApplicationContext提供了ApplicationContext的抽象实现。
下面通过一个具体实例分析AnnotationConfigApplicationContext的初始化过程:
AnnotationConfigApplicationContext annotationConfigApplicationContext
=new AnnotationConfigApplicationContext(Appconfig.class);
构造函数:
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
/*1、这里由于他有父类,所以先去调用父类的构造方法,然后再调用自己的构造方法
*随后在自己的构造方法中初始化一个读取器和扫描器
* this.beanFactory = new DefaultListableBeanFactory();工厂
* */
this();
/*2、注册bean配置类*/
register(componentClasses);
/*刷新上下文*/
refresh();
}
1.this()初始化bean读取器和扫描器
public AnnotationConfigApplicationContext() {
// 在IOC容器中初始化一个注解bean读取器
this.reader = new AnnotatedBeanDefinitionReader(this);
// 在IOC容器中初始化一个按类路径扫描注解bean扫描器
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
GenericApplicationContext工厂部分代码:
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
/**一个工厂,初始化一个BeanFactory
* 理论spring工厂-》产生bean,此处可以将这个DefaultListableBeanFactory就理解为工厂
* Create a new GenericApplicationContext.
* @see #registerBeanDefinition
* @see #refresh
*/
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
2.register(annotatedClasses)
注册bean配置类,AnnotationConfigApplicationContext容器通过AnnotatedBeanDefinitionReader的register方法实现注解Bean的读取,源码如下:
AnnotataionConfigApplicationContext.java中的register方法:
public void register(Class<?>... componentClasses) {
for (Class<?> componentClass : componentClasses) {
registerBean(componentClass);
}
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations.
* @param beanClass the class of the bean
*/
public void registerBean(Class<?> beanClass) {
doRegisterBean(beanClass, null, null, null);
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations, using the given supplier for obtaining a new
* instance (possibly declared as a lambda expression or method reference).
* @param beanClass the class of the bean
* @param instanceSupplier a callback for creating an instance of the bean
* (may be {@code null})
* @since 5.0
*/
public <T> void registerBean(Class<T> beanClass, @Nullable Supplier<T> instanceSupplier) {
doRegisterBean(beanClass, instanceSupplier, null, null);
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations, using the given supplier for obtaining a new
* instance (possibly declared as a lambda expression or method reference).
* @param beanClass the class of the bean
* @param name an explicit name for the bean
* @param instanceSupplier a callback for creating an instance of the bean
* (may be {@code null})
* @since 5.0
*/
public <T> void registerBean(Class<T> beanClass, String name, @Nullable Supplier<T> instanceSupplier) {
doRegisterBean(beanClass, instanceSupplier, name, null);
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations.
* @param beanClass the class of the bean
* @param qualifiers specific qualifier annotations to consider,
* in addition to qualifiers at the bean class level
*/
@SuppressWarnings("unchecked")
public void registerBean(Class<?> beanClass, Class<? extends Annotation>... qualifiers) {
doRegisterBean(beanClass, null, null, qualifiers);
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations.
* @param beanClass the class of the bean
* @param name an explicit name for the bean
* @param qualifiers specific qualifier annotations to consider,
* in addition to qualifiers at the bean class level
*/
@SuppressWarnings("unchecked")
public void registerBean(Class<?> beanClass, String name, Class<? extends Annotation>... qualifiers) {
doRegisterBean(beanClass, null, name, qualifiers);
}
/**
* Register a bean from the given bean class, deriving its metadata from
* class-declared annotations.
* @param beanClass the class of the bean
* @param instanceSupplier a callback for creating an instance of the bean
* (may be {@code null})
* @param name an explicit name for the bean
* @param qualifiers specific qualifier annotations to consider, if any,
* in addition to qualifiers at the bean class level
* @param definitionCustomizers one or more callbacks for customizing the
* factory's {@link BeanDefinition}, e.g. setting a lazy-init or primary flag
* @since 5.0 核心实现逻辑
*/
<T> void doRegisterBean(Class<T> beanClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
// 将bean配置类信息转换成容器中,AnnotatedGenericBeanDefinition数据结构
// AnnotatedGenericBeanDefinition继承自BeanDefinnition,作用是定义一个
// bean的数据结构,下面的getMetadata可以获取到该bean上的注解信息。
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
// @Conditional装配条件判断是否需要跳过注册
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
// 设置回调
abd.setInstanceSupplier(instanceSupplier);
// 解析bean作用域,(单例或者原型),如果有@Scope,则解析@Scope,没有则默认singleton
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
// 作用域写回BeanDefinition数据结构,abd中缺损的情况下为空,将默认
// 值singleton重新赋值到abd
abd.setScope(scopeMetadata.getScopeName());
// 生成bean配置类,beanName;
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
// 通用注解解析到abd结构中,主要处理Lazy,primaryDependsOn,Role,Description这五个注解
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
// @Qualifiers特殊限定符处理
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
// 如果配置@Primary注解,则设置当前Bean为自动装配,Autowired时为首选
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
// 设置当前bean为懒加载
abd.setLazyInit(true);
}
else {
// 其他注解,则添加到abd结构中
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
// 自定义bean添加到BeanDefinition
customizer.customize(abd);
}
// 根据beanName和bean定义信息封装一个beanhold,beanhold就是一个beanname和
// BeanDefinition的映射
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
// 创建代理对象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// BeanDefinitionReaderUtils.registerBeanDefinition内部通过
// DefaultListableBeanFactory.registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
// 按名称将bean定义信息注册到容器中
// 实际上DefaultListableBeanFactory内部维护一个Map<String,BeanDefinition>类型变量beanDefinitionMap
// 用于保存注册bean定义信息,(beanName和beandefinde映射)
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
register方法重点完成了bean配置类本身的解析和注册,处理过程可以分为以下几个步骤:
1、格局bean配置类,使用BeanDefinition解析Bean的定义信息,主要是一些注解信息
2、Bean作用域的处理,默认缺少@Scope注解,解析形成单例
3、借助AnnotationConfigUtils工具类接卸通用注解
4、将bean定义信息以beanName,beandifine键值对的形式注册到ioc容器中。
3.refresh()刷新上下文
refresh()方法在AbstractApplicationContext容器中实现。refresh()方法的作用域是,加载或者刷新当前的配置信息,如果已经存在spring容器,则先销毁之前的容器,重新创建spring容器,载入bean定义,完成容器初始化工作,所以可以看出AnnotationConfigApplicationContext容器是通过调用其父类AbstractApplicationContext的refresh()函数启动整个Ioc容器完成对Bean定义的载入。
AbstractApplicationContext.java中的refresh()方法的实现代码解析如下:
/*refresh是个同步方法,synchronized关键字
*
* */
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.刷新前的预处理
/*准备工作包括设置启动时间,是否激活标识位
初始化属性源(property source)配置
* */
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 获取刷新后的内部bean工厂
/*返回一个factory工厂,为什么要返回一个工厂
因为要对工厂进行初始化
*
* */
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
/*准备工厂,beanFactory的预准备工作
* */
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// beanFactory准备工作完成后,可以做一下后置处理工作
// 空方法,用于在容器中子类的扩展
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
/*子路老师重点方法
在Spring的环境中执行已经被注册的factory processors
*
* */
// 1、扫描scan;2、put进map3、invokeBeanFactoryPostPorcessor{1、custom;2.内置的}
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册beanPostProcessors
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 初始化MessageSource组件(做国际化功能,消息绑定,消息解析)
initMessageSource();
// Initialize event multicaster for this context.
// 初始化时间派发器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 空方法,可以用于子实现在容器刷新时自定义逻辑
onRefresh();
// Check for listener beans and register them.
// 注册时间监听器,将所有项目里面的ApplicationListener注册到容器中来
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化所有剩下的单实例bean,单例bean在初始化容器时创建,原型
// bean在获取时(getBean)时创建
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 完成BeanFactory的初始化创建工作,IOC容器就创建完成。
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
具体分析refresh中的函数逻辑:
1.预先刷新处理
AbstractApplicationContext.preparRefresh()方法
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...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 保存容器中的一些早期的事件
this.earlyApplicationEvents = new LinkedHashSet<>();
}
invokeBeanFactoryPostProcessors 执行bean工厂后置处理器
AbstractApplicationContext. invokeBeanFactoryPostProcessors方法实现:
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 这个地方需要注意getBeanFactoryPostProcessors是获取手动给spring的BeanFactoryPostProcessor
// 自定义并不仅仅是程序员自己写的
// 自己写的可以加companent也可以不加
// 如果加了getBeanFactoryPostProcessors()这个地方得不得,是spring自己扫面的
// 为什么得不到getBeanFactoryPostProcessors(),这个方法是直接获取一个list
// 这个list是在AnnotationConfigApplicationContext被定义
// 所谓的自定义,就是手动调用AnnotataionConfigApplicationContext.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)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
invokeBeanFactoryPostProcessors方法内部执行实现了BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor这两个接口的Process,先获取所有BeanDefinitionRegistryPostProcessor的实现,按照优先级执行;再以相同的策略执行所有BeanFactoryPostProcessor的实现。
invokeBeanFactoryPostProcessors实现:
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement 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.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
这里面在处理BeanDefinitionRegistryPostProcessors时有一个非常重要的过程,AnnotationConfigApplicationContext构造函数在初始化reader时为内部beanFactory容器初始化了一个id为org.springframework.context.annotation.internalConfigurationAnnotationProcessor的组件,这是一个ConfigurationClassPostProcessor组件,用来处理添加@Configuration注解的类,并将Bean定义注册到BeanFactory中。
3.注册BeanPostProcessor(bean的后置处理器),用于拦截bean创建过程
注册后置处理器的大致逻辑是:
1.获取所有的BanPostProcessor
2.根除处理器实现的接口区分出4种类型:
a:实现PriorityOrdered接口的处理器
b.实现Ordered接口的处理器
c.实现MergedBeanDefinitionPostProcessor接口的处理器
d.普通后置处理器
3.按这4种类型一次注册到容器中
4.注册一个特殊的后置处理器
ApplicationListenerDetector,
ApplicationListenerDetector本身也实现了
MergedBeanDefinitionPostProcessor接口,
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
//按优先级分类
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
//先注册实现PriorityOrdered接口的处理器,添加到beanfactory容器中beanFactory.addBeanPostProcessor(postProcessor);
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
//注册实现Ordered接口的处理器
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 注册没有实现Ordered或PriorityOrdered的处理器(nonOrderedPostProcessors)
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.
//最后,重新注册所有internal BeanPostProcessors(实现MergedBeanDefinitionPostProcessor接口的后置处理器
65 sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
//注册ApplicationListenerDetector,用于Bean创建完时检查是否是ApplicationListener
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
###最后完成BeanFactory的初始化创建工作,IOC容器就创建完成
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches();
//初始化和生命周期有关的后置处理器LifecycleProcessor,默认DefaultLifecycleProcessor
initLifecycleProcessor();
// 回调生命周期处理器
getLifecycleProcessor().onRefresh();
//发布容器刷新完成事件:ContextRefreshedEvent
publishEvent(new ContextRefreshedEvent(this));
LiveBeansView.registerApplicationContext(this);
}
以上基本分析了AnnotationConfigApplicationContext容器的初始化过程, Spring容器在启动过程中,会先保存所有注册进来的Bean的定义信息;Spring容器根据条件创建Bean实例,区分单例,还是原型,后置处理器等(后置处理器会在容器创建过程中通过getBean创建,并执行相应的逻辑);Spring容器在创建bean实例后,会使用多种后置处理器来增加bean的功能,比如处理自动注入,AOP,异步,这种后置处理器机制也丰富了bean的功能。