基于 Spring Boot 的 Spring IoC 流程解析

  1. 1. 前言
    1. 1.1. BeanFactory & ApplicationContext
    2. 1.2. BeanDefinition
    3. 1.3. BeanFactoryPostProcessor
    4. 1.4. BeanDefinitionRegistry & BeanDefinitionRegistryPostProcessor
    5. 1.5. BeanPostProcessor
  2. 2. Spring IoC
    1. 2.1. 初始化容器
    2. 2.2. 注册主类
    3. 2.3. 扫描注册 bean
      1. 2.3.1. ConfigurationClassPostProcessor
      2. 2.3.2. ConfigurationClassParser
      3. 2.3.3. ComponentScanAnnotationParser
      4. 2.3.4. ClassPathBeanDefinitionScanner
    4. 2.4. 实例化 bean
      1. 2.4.1. 遍历所有 bean 名称
      2. 2.4.2. 获取 Bean 实例
      3. 2.4.3. 创建 Bean 实例
        1. 2.4.3.1. 整体逻辑
        2. 2.4.3.2. 解析 bean 依赖
        3. 2.4.3.3. 装配 bean 依赖

前言

Spring 的两个核心概念便是 IoC(Inversion of Control) 和 AOP(Aspect-Oriented Programming),其中 IoC 就是控制反转,也被称为依赖注入(dependency injection),主要解决的问题是将业务逻辑与对象创建进行解耦,由之前的在业务逻辑中书写声明和创建对象的代码改为了由 Spring 框架去为我们创建对象,并注入到我们声明在类中属性中去。在了解 Spring IOC 之前,需要先简单 Spring IoC 用到的如下几个重要接口。

BeanFactory & ApplicationContext

AnnotationConfigServletApplicationContext

上图中 AnnotationConfigServletWebServerApplicationContext 是 Spring Boot Web 应用采用的 ApplicationContext 的一个具体实现类。我们就可以看出 ApplicationContext 是 BeanFactory 的一个子接口, ApplicationContext 同样具有 BeanFactory 的定义的功能。其中 BeanFactory 就是 bean 容器,用于注册、获取、删除 Spring 管理的 bean。而 ApplicationContext 则与 Spring AOP 进行了简单集成,新增了扫描我们声明的 bean、以及注入 bean、用于国际化的消息资源处理、事件发布等功能, ApplicationContext 就像是一个集合了各种功能的超级集合。

其中 ApplicationContext 对于 BeanFactory 方法的实现,只不过是内部定义了一个 BeanFactory 类型的属性,在初始化 ApplicationContext 的时候会创建一个 DefaultListableBeanFactory(BeanFactory 的一个实现类),然后调用其对应的方法来实现 BeanFactory 定义的方法。看下图,其中第一张图的方法是在 AbstractApplicationContext 中实现的,后两张图中的方法实现 GenericApplicationContext 中实现的,他们 AnnotationConfigServletWebServerApplicationContext 的父类,在上面 ApplicationContext 的依赖关系图中可以看出。

ApplicationContext 对于 BeanFactory 的实现
ApplicationContext 获取 BeanFactory
Application 封装的 BeanFactory

BeanDefinition

BeanDefinition 便是 bean 实例的描述,例如属性值、构造参数值等。进一步提供的信息依赖于具体实现。在 Spring IoC 中 Spring 会通过配置类从类路径下扫描出 class 文件,并解析成 BeanDefinition 并注册到 BeanDefinitionRegistry,供后续对 bean 进行创建和初始化使用。暂时了解这些就 ok,具体后面看。

BeanFactoryPostProcessor

BeanFactoryPostProcessor 可以叫做 BeanFactory 的后继处理器,可以通过实现该接口,对 BeanFactory 进行相关处理,Spring 会在 ApplicationContext 的 refresh 方法中调用所有已注册到 ApplicationContext 中的 BeanFactoryPostProcessor。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 允许自动以修改一个应用上下文的 bean 定义,调整应用程序上下文底层的 bean 工厂的 bean 属性值。
* 应用上下文可以自动发现其 bean 定义中的 BeanFactoryPostProcessor 并在其他 bean 创建
* 之前应用这些 BeanFactoryPostProcessor。
*
* @author Juergen Hoeller
* @since 06.07.2003
* @see BeanPostProcessor
* @see PropertyResourceConfigurer
*/
@FunctionalInterface
public interface BeanFactoryPostProcessor {

/**
* 在其进行了标准的初始化之后修改应用程序上下文中的内部 bean 工厂,所有的 bean 定义
* 都会被加载但是不会被初始化。允许覆盖或者添加属性,甚至可以覆盖或者添加到渴望初始化
* 的 bean 中。
* @param beanFactory the bean factory used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

BeanDefinitionRegistry & BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistry 便是 Bean 定义注册中心,通过名字便可以了解到应该是存储 Bean 定义的接口,其中 DefaultListableBeanFactory 便实现了 BeanDefinitionRegistry 接口的相关方法。

BeanDefinitionRegistryPostProcessor 可以被称为 Bean 定义注册中心后继处理器,是 BeanFactoryPostProcessor 的子接口,增加了 postProcessBeanDefinitionRegistry 方法,可以对入参的 BeanDefinitionRegistry 进行处理。也是在 ApplicationContext 的 refresh 方法中统一调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package org.springframework.beans.factory.support;
/**
*
* 注释大概翻译如下:
* 扩展自 BeanFactoryPostProcessor 的标准 SPI,允许常规的 BeanFactoryPostProcessor 启动之前注册
* 其它的 bean 定义,大部分情况下,BeanDefinitionRegistryPostProcessor 注册了一些
* BeanFactoryPostProcessor 实例的 bean 定义。
*
* 其中 ConfigurationClassPostProcessor 应该便是实现了该接口扫描 bean 并将其定义加载到 Spring 容器中。
*
* 我们知道对于 MyBatis 不需要使用 @Repository 标识 DAO 的接口也是可以将类注入到 Spring 容器中的,
* 应该就是 MyBatis 提供的 starter 中某个类实现了该接口。
*
* @author Juergen Hoeller
* @since 3.0.1
* @see org.springframework.context.annotation.ConfigurationClassPostProcessor
*/
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

/**
* 在其进行了标准初始化之后修改应用程序上下文内部的 bean 定义注册中心,所有的常规 bean 定义都会
* 被加载,但是不会初始化。允许在下一次后续处理之前进一步添加 bean 定义。大概理解来说应该就是
* 这个方法实现了扫描我们声明需要由 Spring 管理的类并加载达 bean 容器中的功能。
* 其中
* @param registry the bean definition registry used by the application context
* @throws org.springframework.beans.BeansException in case of errors
*/
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

BeanPostProcessor

按照上面的套路,那么 BeanPostProcessor 肯定也就是 Bean 后继处理器了。其中 BeanPostProcessor 有两个方法,postProcessBeforeInitialization 和 postProcessAfterInitialization,其中 postProcessBeforeInitialization 是初始化前的后继处理方法,主要用于为对象实例注入 bean,后者是初始化后的后继处理方法,用于创建对象代理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* 允许自定义修改一个新的 bean 实例的工厂钩子,例如校验接口标记或者为其创建代理对象。
*
* ApplicationContext 可以在他们的 bean 定义中自动发现 BeanPostProcessor 并在之后创建任何 bean
* 时应用他们。普通的 bean 工厂允许通过编程式的方式注册后继处理器,并通过该工厂在所有 bean 被创建时应用。
*
* 典型的,通过接口标记填充 bean 等其他类似后继处理器可以实现 postProcessBeforeInitialization,
* 当使用代理封装 bean 时一般实现 postProcessAfterInitialization。
*/
public interface BeanPostProcessor {

/**
* 在 bean 初始化回调(例如 InitializingBean 的 afterPropertiesSet 或者其他自动以初始化方法)之前
* 为给定的新的 bean 实例应用 BeanPostProcessor。该 bean 的属性值将会已经被设置,返回的可能是封装了原始
* bean 的代理 bean。
*
* 默认实现发挥给定 bean 自己。
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

/**
* 在 bean 初始化回调(例如 InitializingBean 的 afterPropertiesSet 或者其他自动以初始化方法)之后
* 为给定的新的 bean 实例应用 BeanPostProcessor。该 bean 的属性值将会已经被设置,返回的可能是封装了原始
* bean 的代理 bean。
*
* 对于 FactoryBean,该回调会为 FactoryBean 实例和通过该 FactoryBean 实例创建的对象都进行调用。
* 该后继处理通过校验相应的 bean 是否是 FactoryBean 的实例决定是否应用在 FactoryBean 实例和其创建
* 的对象其中之一,还是两者都应用。
*
* 与所有其他 BeanPostProcessor 回调相比,在 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
* 方法触发的短路之后,也将调用此回调。
*
* @param bean the new bean instance
* @param beanName the name of the bean
* @return the bean instance to use, either the original or a wrapped one;
* if {@code null}, no subsequent BeanPostProcessors will be invoked
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
* @see org.springframework.beans.factory.FactoryBean
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

}

Spring IoC

Spring IoC 的整体流程分为这样几部,首先创建初始化 bean 容器、将主类 BeanDefinition 注册到容器中、通过主类配置扫描
class 文件解析成 BeanDefinition 注册到 bena 容器,通过 BeanDefinition 创建初始化 bean 实例。

DcdcApplication

上图便是一个简单的 Spring Boot 应用的启动类,也就是主类,我们可以看到调用了 SpringApplication 类级别(static)的 run 方法,其实现首先是初始化创建一个 SpringApplication 对象然后调用其 run 方法(对象级别,非 static)。下段代码是最终调用的 run 方法的实现。其中相关流程实现的方法在方面进行了注释。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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);
// 创建 ApplicationContext,初始化容器
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 准备上下文,将主类 bean 定义注册到上下文中
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
// 刷新上下文,扫描并注册 bean 并进行实例化
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}

try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}

接下来我们就看下每个流程的具体实现。

初始化容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
+ "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";

/**
* 创建 ApplicationContext 的逻辑很简单,整体来说就是根据不同的应用类型创建不同的 ApplicationContext。
*/
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
// 普通的 Spring Boot Web 引用,走的是这个分支
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
// 创建 ApplicationContext 的对象实例
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

创建 ApplicationContext 的逻辑很简单,根绝不同的应用类型选择不同的 ApplicationContext 实现类进行创建,而 Spring Boot 使用的是 AnnotationConfigServletWebServerApplicationContext 类,我们来看下其构造函数的初始化逻辑。

AnnotationConfigServletWebServerApplicationContext 构造函数

初始化了 reader、scanner 两个属性,其功能在他们的注释上有描述,其中 scanner 大概功能是将 classpath 下带有 @Component、@Repository、@Service、@Controller 注解的类找到并将其 bean 定义注册到给定的注册中心(BeanFactory 或者 ApplicationContext)去。而 reader 的作用相同,只不过只针对明确注册的类。我们来看下他们的初始化逻辑。

ClassPathBeanDefinitionScanner

其中 scanner 的仅仅是初始化了 registry、includeFilters、environment、resourceLoader 四个属性,其中 registry 为 AnnotationConfigServletWebServerApplicationContext 对象,其余使用的默认值。

AnnotatedBeanDefinitionReader

其中 AnnotatedBeanDefinitionReader 只是初始化了 registry 和 conditionEvaluator 两个属性,不过还调用了 AnnotationConfigUtils.registerAnnotationConfigProcessor 方法,这是重点,我们需要看下其中的逻辑。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/**
* The bean name of the internally managed Configuration annotation processor.
*/
public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalConfigurationAnnotationProcessor";

/**
* The bean name of the internally managed BeanNameGenerator for use when processing
* {@link Configuration} classes. Set by {@link AnnotationConfigApplicationContext}
* and {@code AnnotationConfigWebApplicationContext} during bootstrap in order to make
* any custom name generation strategy available to the underlying
* {@link ConfigurationClassPostProcessor}.
* @since 3.1.1
*/
public static final String CONFIGURATION_BEAN_NAME_GENERATOR =
"org.springframework.context.annotation.internalConfigurationBeanNameGenerator";

/**
* The bean name of the internally managed Autowired annotation processor.
*/
public static final String AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalAutowiredAnnotationProcessor";

/**
* The bean name of the internally managed Required annotation processor.
* @deprecated as of 5.1, since no Required processor is registered by default anymore
*/
@Deprecated
public static final String REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalRequiredAnnotationProcessor";

/**
* The bean name of the internally managed JSR-250 annotation processor.
*/
public static final String COMMON_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalCommonAnnotationProcessor";

/**
* The bean name of the internally managed JPA annotation processor.
*/
public static final String PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME =
"org.springframework.context.annotation.internalPersistenceAnnotationProcessor";

private static final String PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME =
"org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor";

/**
* The bean name of the internally managed @EventListener annotation processor.
*/
public static final String EVENT_LISTENER_PROCESSOR_BEAN_NAME =
"org.springframework.context.event.internalEventListenerProcessor";

/**
* The bean name of the internally managed EventListenerFactory.
*/
public static final String EVENT_LISTENER_FACTORY_BEAN_NAME =
"org.springframework.context.event.internalEventListenerFactory";
/**
* 注册所有注解相关的后续处理器到给定的 bean 定义注册中心
* @param registry the registry to operate on
*/
public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
registerAnnotationConfigProcessors(registry, null);
}

/**
* Register all relevant annotation post processors in the given registry.
*
* @param registry the registry to operate on
* @param source the configuration source element (already extracted)
* that this registration was triggered from. May be {@code null}.
* @return a Set of BeanDefinitionHolders, containing all bean definitions
* that have actually been registered by this call
*/
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
BeanDefinitionRegistry registry, @Nullable Object source) {

// 获取 BeanFactory
DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
if (beanFactory != null) {
// 注册依赖顺序比较器
if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
}
// 设置自动注入候选解析器
if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
}
}

Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

// 这里需要注意,此处注册了 ConfigurationClassPostProcessor 的 bean 定义,该
// 类会找到 Spring Boot 服务主类所在包及其子包下的下的所有声明的类,然后将他们进
// 行解析并将 bean 定义注册到 BeanFactory 中去。可以通过右侧的导航栏跳转到
// 3.2.1 通过注释简单看下 ConfigurationClassPostProcessor 的大致实现
if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}

// 注册 AutowiredAnnotationBeanPostProcessor, 该类的主要作用是解析 bean 依赖(被 @Autowire,@Value,@Inject 标识的属性),
// 并注入 bean 依赖。
if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
}

// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
}

// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition();
try {
def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
AnnotationConfigUtils.class.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
}
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
}

if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
}

if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
}

return beanDefs;
}

千万不要忘了,系统还默认调用了父类的构造函数,我们也需要看下。

GenericApplicationContext 构造函数

其中父类中还初始化了 BeanFactory,因此整个初始化流程暂时需要我们记住的就是创建了 BeanFactory、注册了一个 ConfigurationClassPostProcessor 用于后续扫描 bean 并注册 bean 定义。

注册主类

注册主类 BeanDefinition,后续通从 bean 容器中读取其 BeanDefinition,作为扫描 BeanDefinition 的初始点。其注册主类 BeanDefinition 是在 SpringApplication 的 load(ApplicationContext context, Object[] sources) 方法中实现的,该方法会在 prepareContext 中被调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
// 设置环境信息
context.setEnvironment(environment);
// 处理 ApplicationContext
postProcessApplicationContext(context);
// 调用已注册的 ApplicationContextInitializer 处理 ApplicationContext
applyInitializers(context);
// 发出上下文准备完毕的事件
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// 注册系统相关的单例 bean
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// 获取并加载主类
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
// 发出主类加载完毕的事件
listeners.contextLoaded(context);
}

/**
* 将给定 bean 加载到应用上下文
* @param context the context to load beans into
* @param sources the sources to load
*/
protected void load(ApplicationContext context, Object[] sources) {
if (logger.isDebugEnabled()) {
logger.debug(
"Loading source " + StringUtils.arrayToCommaDelimitedString(sources));
}
// 创建 BeanDefinition 加载器
BeanDefinitionLoader loader = createBeanDefinitionLoader(
getBeanDefinitionRegistry(context), sources);
// 设置 bean 名称生成器
if (this.beanNameGenerator != null) {
loader.setBeanNameGenerator(this.beanNameGenerator);
}
// 设置资源加载器
if (this.resourceLoader != null) {
loader.setResourceLoader(this.resourceLoader);
}
// 设置环境
if (this.environment != null) {
loader.setEnvironment(this.environment);
}
// 通过 BeanDefinition 加载器注册主类 BeanDefinition
loader.load();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**
* 加载底层源类型,包括 XML 和 Java 配置类。作为 AnnotatedBeanDefinitionReader、XmlBeanDefinitionReader 和
* ClassPathBeanDefinitionScanner 的简单外观。
*
* @author Phillip Webb
* @see #setBeanNameGenerator(BeanNameGenerator)
*/
class BeanDefinitionLoader {

private final Object[] sources;

private final AnnotatedBeanDefinitionReader annotatedReader;

private final XmlBeanDefinitionReader xmlReader;

private BeanDefinitionReader groovyReader;

private final ClassPathBeanDefinitionScanner scanner;

private ResourceLoader resourceLoader;

/**
* 创建一个新的将要把 bean 加载到指定 BeanDefinitionRegistry 的 BeanDefinitionLoader。
* @param registry the bean definition registry that will contain the loaded beans
* @param sources the bean sources
*/
BeanDefinitionLoader(BeanDefinitionRegistry registry, Object... sources) {
Assert.notNull(registry, "Registry must not be null");
Assert.notEmpty(sources, "Sources must not be empty");
// 设置要加载的类
this.sources = sources;
// 设置读取 JavaConfig 的读取器,其中初始化 ApplicationContext 中也有创建该类的对象
this.annotatedReader = new AnnotatedBeanDefinitionReader(registry);
// 设置读取 XML 的读取器
this.xmlReader = new XmlBeanDefinitionReader(registry);
// 根据条件决定是否加载 Groovy bean 定义的读取器
if (isGroovyPresent()) {
this.groovyReader = new GroovyBeanDefinitionReader(registry);
}
// 设置类路径 bean 定义扫描器,其中初始化 ApplicationContext 中也有创建该类的对象
this.scanner = new ClassPathBeanDefinitionScanner(registry);
// 设置过滤器
this.scanner.addExcludeFilter(new ClassExcludeFilter(sources));
}

/**
* 将类加载到读取器
* @return the number of loaded beans
*/
public int load() {
int count = 0;
// 遍历需要注册的类,循环调用 load 方法。
for (Object source : this.sources) {
count += load(source);
}
return count;
}

/**
* 根据 source 类型调用不同实现
*/
private int load(Object source) {
Assert.notNull(source, "Source must not be null");
if (source instanceof Class<?>) {
// 加载主类走这一步
return load((Class<?>) source);
}
if (source instanceof Resource) {
return load((Resource) source);
}
if (source instanceof Package) {
return load((Package) source);
}
if (source instanceof CharSequence) {
return load((CharSequence) source);
}
throw new IllegalArgumentException("Invalid source type " + source.getClass());
}

/**
* 加载 Java 配置类
*/
private int load(Class<?> source) {
// 校验是否是 Groovy 类,如果是则调用架子啊 Groovy 的实现
if (isGroovyPresent()
&& GroovyBeanDefinitionSource.class.isAssignableFrom(source)) {
// Any GroovyLoaders added in beans{} DSL can contribute beans here
GroovyBeanDefinitionSource loader = BeanUtils.instantiateClass(source,
GroovyBeanDefinitionSource.class);
load(loader);
}
// 校验是否被 @Component 注解标注
if (isComponent(source)) {
// 调用注解读取器注册 bean 定义
this.annotatedReader.register(source);
return 1;
}
return 0;
}

private boolean isComponent(Class<?> type) {
// This has to be a bit of a guess. The only way to be sure that this type is
// eligible is to make a bean definition out of it and try to instantiate it.
if (AnnotationUtils.findAnnotation(type, Component.class) != null) {
return true;
}
// Nested anonymous classes are not eligible for registration, nor are groovy
// closures
if (type.getName().matches(".*\\$_.*closure.*") || type.isAnonymousClass()
|| type.getConstructors() == null || type.getConstructors().length == 0) {
return false;
}
return true;
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class AnnotatedBeanDefinitionReader {

/**
* 循环注册 annotatedClasses
*
* @param annotatedClasses one or more annotated classes,
* e.g. {@link Configuration @Configuration} classes
*/
public void register(Class<?>... annotatedClasses) {
// 循环注册
for (Class<?> annotatedClass : annotatedClasses) {
registerBean(annotatedClass);
}
}

/**
* 注册指定 class 的 bean 定义
*
* @param annotatedClass the class of the bean
*/
public void registerBean(Class<?> annotatedClass) {
doRegisterBean(annotatedClass, null, null, null);
}

/**
* 通过给定的 bean class 注册一个 bean 定义,从 class 中声明的注解推导出元数据
*/
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

// 创建一个 bean 定义
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
// 校验 @Condition 中的条件是否通过
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}

abd.setInstanceSupplier(instanceSupplier);
// 设置作用域
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
// 设置 bean 名称生成器
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

// 进行通用的 bean 定义处理
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
// 根据 qualifiers 设置相关属性
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
// 为 bean 定义设置给定的定制器
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}

// 创建 bean 定义持有器
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
// 设置作用域代理
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
// 注册 bean 定义
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
}

扫描注册 bean

接下来便是扫描注册所有我们声明的 Bean。在 refreContext 中调用了 ApplicationContext 的 refresh 来实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 刷新 context,我们可以看到主要实现就是调用了 applicationContext 的 refresh 方法以及
* 注册 JVM 关闭时的钩子方法
*/
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}

一路跟踪找到 refresh 方法,实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@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.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);

// 之前已经了解了 BeanFactoryPostProcessor 的作用,便是在此处统一调用 BeanFactoryPostProcessor
// 将 bean 注册到 bean 容器中,具体实现看下段代码
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.
initMessageSource();

// Initialize event multicaster for this context.
initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.
onRefresh();

// Check for listener beans and register them.
registerListeners();

// 初始化所有单例 bean,具体实现在下节
finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.
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();
}
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/**
* 调用所有已注册的 BeanFactoryPostProcessor
*/
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

/******************************************************************/
/*****************执行给定的 BeanFactoryPostProcessor****************/
/******************************************************************/

// 所有调用过 postProcessBeanDefinitionRegistry 方法的 bean
Set<String> processedBeans = new HashSet<>();

// 如果参数 beanFactory 实现了 BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
// 类型强转
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 所有常规的 BeanFactoryPostProcessor 实现类,及实现的接口是 BeanFactoryPostProcessor,
// 而非 BeanFactoryPostProcessor 的子接口(BeanDefinitionRegistryPostProcessor)
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 所有的 BeanDefinitionRegistry 实现类
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

// 先执行参数 beanFactoryPostProcessors 中的 BeanFactoryPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 类型判断
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 如果是 BeanDefinitionRegistry,则类型强转
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 调用 postProcessorBeanDefinitionRegistry 方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 添加到 registryProcessors 集合中
registryProcessors.add(registryProcessor);
}
else {
// 直接添加到 BeanFactoryPostProcessor 中去
regularPostProcessors.add(postProcessor);
}
}

// 区分 PriorityOrdered、Ordered 和其余的 BeanDefinitionRegistryPostProcessor 的集合,
// 每次统计后将 bean 存入到该集合,然后调用,最后清空集合。
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

// 首先调用实现了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessor
// 获取 BeanDefinitionRegistryPostProcessor 类型的 bean 名称
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 遍历所有名字
for (String ppName : postProcessorNames) {
// 判断与 PriorityOrdered 类型是否匹配,上面 ConfigurationClassPostProcessor
// 便实现了 PriorityOrdered 接口
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 查询 bean 并添加到 currentRegistryProcessors 集合中
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 添加到 processedBeans 集合中
processedBeans.add(ppName);
}
}
// 进行排序,按照优先级调用
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 将所有实现了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor
// 添加到 registryProcessors 中
registryProcessors.addAll(currentRegistryProcessors);
// 调用 postProcessBeanDefinitionRegistry 方法,invokeBeanDefinitionRegistryPostProcessors
// 的实现就是遍历参数 currentRegistryProcessors,调用每个元素的 postProcessBeanDefinitionRegistry
// 方法,并将参数 registry 传入该方法。其中 ConfigurationClassPostProcessor 便会在此处执行!!!
// 同样可以通过右侧导航栏查看 ConfigurationClassPostProcessor 的 postProcessBeanDefinitionRegistry
// 的具体实现
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空 currentRegistryProcessors 集合
currentRegistryProcessors.clear();

// 接下来调用实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor 实例,流程与上面基本一致
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;
// 查询所有 BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
// 遍历 postProcessorNames
for (String ppName : postProcessorNames) {
// 如果为执行过则添加到 currentRegistryProcessors,并将 reiterate 设置为 true
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
// 排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加到已执行的 list 中
registryProcessors.addAll(currentRegistryProcessors);
// 执行剩余所有 BeanDefinitionRegistry
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空 currentRegistryProcessors
currentRegistryProcessors.clear();
}

// 执行 BeanDefinitionRegistryPostProcessor 的 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 执行常规 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}

else {
// 如果非 BeanDefinitionRegistry 则直接执行所有 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}

/******************************************************************/
/****************执行已注册的 BeanFactoryPostProcessor***************/
/******************************************************************/

// 这里没有实例化 FactoryBean,我们需要留下所有没有实例化的常规 bean 让 BeanFactory
// 后继处理器来应用他们
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);


// 分离实现了 PriorityOrdered、Ordered 和其他的 BeanFactoryPostProcessor。
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// 遍历所有已注册 BeanFactoryPostProcessor
for (String ppName : postProcessorNames) {
// 已执行过得跳过
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
// 分离不同 BeanFactoryPostProcessor
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);
}
}

// 首先执行实现了 PriorityOrdered 的 BeanFactoryPostProcessors
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// 接下来执行实现了 Ordered 的 BeanFactoryPostProcessors
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);

// 清空合并 bean 定义的缓存,后处理后可能修改了原始的元数据,例如替换 placeholders
beanFactory.clearMetadataCache();
}

ConfigurationClassPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
* BeanFactoryPostProcessor 用于带有 @Configuration 注解的类的引导处理。
*
* 当使用 `<context:annotation-config/>` 或者 `<context:component-scan/>` 时该
* ConfigurationClassPostProcessor 会被默认注册,如果是其他方式可能需要手动声明其他
* 的 BeanFactoryPostProcessor。
*
* 该类是 BeanDefinitionRegistryPostProcessor 的一个具体实现,其中可以通过导航栏
* 跳转到 BeanDefinitionRegistryPostProcessor 简单看下具体功能。
*/
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware {

private static final String IMPORT_REGISTRY_BEAN_NAME =
ConfigurationClassPostProcessor.class.getName() + ".importRegistry";


private final Log logger = LogFactory.getLog(getClass());

private SourceExtractor sourceExtractor = new PassThroughSourceExtractor();

private ProblemReporter problemReporter = new FailFastProblemReporter();

@Nullable
private Environment environment;

private ResourceLoader resourceLoader = new DefaultResourceLoader();

@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();

private MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();

private boolean setMetadataReaderFactoryCalled = false;

private final Set<Integer> registriesPostProcessed = new HashSet<>();

private final Set<Integer> factoriesPostProcessed = new HashSet<>();

@Nullable
private ConfigurationClassBeanDefinitionReader reader;

private boolean localBeanNameGeneratorSet = false;

/* Using short class names as default bean names */
private BeanNameGenerator componentScanBeanNameGenerator = new AnnotationBeanNameGenerator();

/* Using fully qualified class names as default bean names */
private BeanNameGenerator importBeanNameGenerator = new AnnotationBeanNameGenerator() {
@Override
protected String buildDefaultBeanName(BeanDefinition definition) {
String beanClassName = definition.getBeanClassName();
Assert.state(beanClassName != null, "No bean class name set");
return beanClassName;
}
};


// 最低优先级,PriorityOrdered 接口方法的实现
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE; // within PriorityOrdered
}

/**
* Set the {@link SourceExtractor} to use for generated bean definitions
* that correspond to {@link Bean} factory methods.
*/
public void setSourceExtractor(@Nullable SourceExtractor sourceExtractor) {
this.sourceExtractor = (sourceExtractor != null ? sourceExtractor : new PassThroughSourceExtractor());
}

/**
* Set the {@link ProblemReporter} to use.
* <p>Used to register any problems detected with {@link Configuration} or {@link Bean}
* declarations. For instance, an @Bean method marked as {@code final} is illegal
* and would be reported as a problem. Defaults to {@link FailFastProblemReporter}.
*/
public void setProblemReporter(@Nullable ProblemReporter problemReporter) {
this.problemReporter = (problemReporter != null ? problemReporter : new FailFastProblemReporter());
}

/**
* Set the {@link MetadataReaderFactory} to use.
* <p>Default is a {@link CachingMetadataReaderFactory} for the specified
* {@linkplain #setBeanClassLoader bean class loader}.
*/
public void setMetadataReaderFactory(MetadataReaderFactory metadataReaderFactory) {
Assert.notNull(metadataReaderFactory, "MetadataReaderFactory must not be null");
this.metadataReaderFactory = metadataReaderFactory;
this.setMetadataReaderFactoryCalled = true;
}

/**
* Set the {@link BeanNameGenerator} to be used when triggering component scanning
* from {@link Configuration} classes and when registering {@link Import}'ed
* configuration classes. The default is a standard {@link AnnotationBeanNameGenerator}
* for scanned components (compatible with the default in {@link ClassPathBeanDefinitionScanner})
* and a variant thereof for imported configuration classes (using unique fully-qualified
* class names instead of standard component overriding).
* <p>Note that this strategy does <em>not</em> apply to {@link Bean} methods.
* <p>This setter is typically only appropriate when configuring the post-processor as
* a standalone bean definition in XML, e.g. not using the dedicated
* {@code AnnotationConfig*} application contexts or the {@code
* <context:annotation-config>} element. Any bean name generator specified against
* the application context will take precedence over any value set here.
* @since 3.1.1
* @see AnnotationConfigApplicationContext#setBeanNameGenerator(BeanNameGenerator)
* @see AnnotationConfigUtils#CONFIGURATION_BEAN_NAME_GENERATOR
*/
public void setBeanNameGenerator(BeanNameGenerator beanNameGenerator) {
Assert.notNull(beanNameGenerator, "BeanNameGenerator must not be null");
this.localBeanNameGeneratorSet = true;
this.componentScanBeanNameGenerator = beanNameGenerator;
this.importBeanNameGenerator = beanNameGenerator;
}

@Override
public void setEnvironment(Environment environment) {
Assert.notNull(environment, "Environment must not be null");
this.environment = environment;
}

@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
Assert.notNull(resourceLoader, "ResourceLoader must not be null");
this.resourceLoader = resourceLoader;
if (!this.setMetadataReaderFactoryCalled) {
this.metadataReaderFactory = new CachingMetadataReaderFactory(resourceLoader);
}
}

@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = beanClassLoader;
if (!this.setMetadataReaderFactoryCalled) {
this.metadataReaderFactory = new CachingMetadataReaderFactory(beanClassLoader);
}
}


/**
* 扫描配置中声明的类,解析出 bean 定义并注册到 registry
*/
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
// 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);
}
// 添加到 registriesPostProcessed 中
this.registriesPostProcessed.add(registryId);

// 解析配置类
processConfigBeanDefinitions(registry);
}

/**
* Prepare the Configuration classes for servicing bean requests at runtime
* by replacing them with CGLIB-enhanced subclasses.
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + beanFactory);
}
this.factoriesPostProcessed.add(factoryId);
if (!this.registriesPostProcessed.contains(factoryId)) {
// BeanDefinitionRegistryPostProcessor hook apparently not supported...
// Simply call processConfigurationClasses lazily at this point then.
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
}

enhanceConfigurationClasses(beanFactory);
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}

/**
* 基于配置类的注册中心构建和校验配置模块
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
// BeanDefinitionHolder 集合
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
// 已注册的 bean 定义名称
String[] candidateNames = registry.getBeanDefinitionNames();

// 遍历 bean 名称
for (String beanName : candidateNames) {
// 获取 bean 定义
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
// 校验 bean 是否为配置 bean
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
// 如果是候选配置 bean 则创建对应的 BeanDefinitionHolder 并添加到集合中
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}

// 如果 @Configuration 类没有找到则立即返回,此时应该只能找到在 prepareContext 中注册到的主类
if (configCandidates.isEmpty()) {
return;
}

// 将找到的配置类进行排序
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});

// 找到应用程序上下文提供的自定义的 bean 名称生成策略
SingletonBeanRegistry sbr = null;
// 判断是否是单例 bean 注册中心
if (registry instanceof SingletonBeanRegistry) {
类型强转
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
// 获取 bean 名称生成器
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
// 不为空则设置
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}

// 如果环境为空则创建一个标准环境
if (this.environment == null) {
this.environment = new StandardEnvironment();
}

// 创建 @Configuration 类解析器
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);

// 将候选配置类集合转换为 Set
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
// 已解析的配置类
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
// 使用解析器解析候选 bean 定义
parser.parse(candidates);
// 解析完成,校验每个配置类(类不能为 final,非静态方法需要可以被重写等)
parser.validate();

Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);

// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);

candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
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);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());

// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}

if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}

/**
* Post-processes a BeanFactory in search of Configuration class BeanDefinitions;
* any candidates are then enhanced by a {@link ConfigurationClassEnhancer}.
* Candidate status is determined by BeanDefinition attribute metadata.
* @see ConfigurationClassEnhancer
*/
public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
for (String beanName : beanFactory.getBeanDefinitionNames()) {
BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
if (!(beanDef instanceof AbstractBeanDefinition)) {
throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
}
else if (logger.isInfoEnabled() && beanFactory.containsSingleton(beanName)) {
logger.info("Cannot enhance @Configuration bean definition '" + beanName +
"' since its singleton instance has been created too early. The typical cause " +
"is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
"return type: Consider declaring such methods as 'static'.");
}
configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
}
}
if (configBeanDefs.isEmpty()) {
// nothing to enhance -> return immediately
return;
}

ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
AbstractBeanDefinition beanDef = entry.getValue();
// If a @Configuration class gets proxied, always proxy the target class
beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
try {
// Set enhanced subclass of the user-specified bean class
Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
if (configClass != null) {
Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
if (configClass != enhancedClass) {
if (logger.isTraceEnabled()) {
logger.trace(String.format("Replacing bean definition '%s' existing class '%s' with " +
"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
}
beanDef.setBeanClass(enhancedClass);
}
}
}
catch (Throwable ex) {
throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
}
}
}


private static class ImportAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

private final BeanFactory beanFactory;

public ImportAwareBeanPostProcessor(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}

@Override
public PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {
// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's
// postProcessProperties method attempts to autowire other configuration beans.
if (bean instanceof EnhancedConfiguration) {
((EnhancedConfiguration) bean).setBeanFactory(this.beanFactory);
}
return pvs;
}

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if (bean instanceof ImportAware) {
ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
AnnotationMetadata importingClass = ir.getImportingClassFor(bean.getClass().getSuperclass().getName());
if (importingClass != null) {
((ImportAware) bean).setImportMetadata(importingClass);
}
}
return bean;
}
}

}

ConfigurationClassParser

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
/**
* 解析一个配置类定义,填充到一个 ConfigurationClass 对象的集合中。解析一个单独配置类的结果可能是
* 任意数量的配置类对象,因为一个配置类可能会使用 @Import 注解导入其他的配置类。
*
* <p>This class helps separate the concern of parsing the structure of a Configuration
* class from the concern of registering BeanDefinition objects based on the content of
* that model (with the exception of {@code @ComponentScan} annotations which need to be
* registered immediately).
*
* <p>This ASM-based implementation avoids reflection and eager class loading in order to
* interoperate effectively with lazy class loading in a Spring ApplicationContext.
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Phillip Webb
* @author Sam Brannen
* @author Stephane Nicoll
* @since 3.0
* @see ConfigurationClassBeanDefinitionReader
*/
class ConfigurationClassParser {

private static final PropertySourceFactory DEFAULT_PROPERTY_SOURCE_FACTORY = new DefaultPropertySourceFactory();

private static final Comparator<DeferredImportSelectorHolder> DEFERRED_IMPORT_COMPARATOR =
(o1, o2) -> AnnotationAwareOrderComparator.INSTANCE.compare(o1.getImportSelector(), o2.getImportSelector());


private final Log logger = LogFactory.getLog(getClass());

private final MetadataReaderFactory metadataReaderFactory;

private final ProblemReporter problemReporter;

private final Environment environment;

private final ResourceLoader resourceLoader;

private final BeanDefinitionRegistry registry;

private final ComponentScanAnnotationParser componentScanParser;

private final ConditionEvaluator conditionEvaluator;

/**
* 以解析的配置类
*/
private final Map<ConfigurationClass, ConfigurationClass> configurationClasses = new LinkedHashMap<>();

private final Map<String, ConfigurationClass> knownSuperclasses = new HashMap<>();

private final List<String> propertySourceNames = new ArrayList<>();

private final ImportStack importStack = new ImportStack();

private final DeferredImportSelectorHandler deferredImportSelectorHandler = new DeferredImportSelectorHandler();


/**
* Create a new {@link ConfigurationClassParser} instance that will be used
* to populate the set of configuration classes.
*/
public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
ProblemReporter problemReporter, Environment environment, ResourceLoader resourceLoader,
BeanNameGenerator componentScanBeanNameGenerator, BeanDefinitionRegistry registry) {

this.metadataReaderFactory = metadataReaderFactory;
this.problemReporter = problemReporter;
this.environment = environment;
this.resourceLoader = resourceLoader;
this.registry = registry;
this.componentScanParser = new ComponentScanAnnotationParser(
environment, resourceLoader, componentScanBeanNameGenerator, registry);
this.conditionEvaluator = new ConditionEvaluator(registry, environment, resourceLoader);
}

/**
* 给定候选 bean 定义并对其进行解析
*/
public void parse(Set<BeanDefinitionHolder> configCandidates) {
// 遍历候选 bean 定义
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try {
// 检验类型 并进行解析 并通过不同的方式进行解析,其中主类为 AnnotationBeanDefinition
if (bd instanceof AnnotatedBeanDefinition) {
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}

this.deferredImportSelectorHandler.process();
}

protected final void parse(@Nullable String className, String beanName) throws IOException {
Assert.notNull(className, "No bean class name for configuration class bean definition");
MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
processConfigurationClass(new ConfigurationClass(reader, beanName));
}

protected final void parse(Class<?> clazz, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(clazz, beanName));
}

/**
* 通过给定的 AnnotationMetadata 和 beanName 解析
*/
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
// 通过metadata 和 beanName 创建一个ConfigurationClass 并对其进行解析
processConfigurationClass(new ConfigurationClass(metadata, beanName));
}

/**
* 校验每一个已解析的 ConfigurationClass
* @see ConfigurationClass#validate
*/
public void validate() {
for (ConfigurationClass configClass : this.configurationClasses.keySet()) {
configClass.validate(this.problemReporter);
}
}

public Set<ConfigurationClass> getConfigurationClasses() {
return this.configurationClasses.keySet();
}

/**
* 解析 ConfigurationClass,其中 ConfigurationClass 就是一个带有 @Configuration 的类的描述
*/
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
// 校验是否满足解析类的条件
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}

// 校验是否存在
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
// 参数 configClass 是否带有 @Import 注解
if (configClass.isImported()) {
//
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}

// 将 ConfigurationClass 转换成 SourceClass 统一处理
SourceClass sourceClass = asSourceClass(configClass);
do {
// 解析配置类,将 bean 定义注册到 BeanDefinitionRegistry
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);
// 将配置类放到 map
this.configurationClasses.put(configClass, configClass);
}

/**
* 处理和解析并构建一个完成的 ConfigurationClass 通过从 SourceClass 读取注解、内部类和方法。当相关源被发现时
* 该方法可以被多次调用。
* @param configClass the configuration class being build
* @param sourceClass a source class
* @return the superclass, or {@code null} if none found or previously processed
*/
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {

// 如果被 @Component 注解标识则先读取父类
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// 解析内部类
processMemberClasses(configClass, sourceClass);
}

// 处理 @PropertySource 注解
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}

// 处理 @ComponentScan 注解
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
// 不为空且和满足解析条件
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
// 遍历所有的 @ComponentScan
for (AnnotationAttributes componentScan : componentScans) {
// 通过 ComponentScanParser 解析出所有的 bean 定义,在此处,已经将所有的 bean 定义解析出来
// 并注册到 BeanFactory 中去了。
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// 遍历解析出的结果,如果包含配置类则对其进行解析
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}

if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}

// 处理 @Import 注解
processImports(configClass, sourceClass, getImports(sourceClass), true);

// 处理 @ImportResource 注解
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}

// 处理各个带有 @Bean 注解的方法
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}

// 处理接口中的默认方法
processInterfaces(configClass, sourceClass);

// 如果存在则处理父类
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
// 如果存在父类则返回父类重新调用 doProcessConfigurationClass 方法
return sourceClass.getSuperClass();
}
}

// 没有父类则处理完成
return null;
}

/**
* Register member (nested) classes that happen to be configuration classes themselves.
*/
private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
Collection<SourceClass> memberClasses = sourceClass.getMemberClasses();
if (!memberClasses.isEmpty()) {
List<SourceClass> candidates = new ArrayList<>(memberClasses.size());
for (SourceClass memberClass : memberClasses) {
if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
candidates.add(memberClass);
}
}
OrderComparator.sort(candidates);
for (SourceClass candidate : candidates) {
if (this.importStack.contains(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
processConfigurationClass(candidate.asConfigClass(configClass));
}
finally {
this.importStack.pop();
}
}
}
}
}

/**
* Register default methods on interfaces implemented by the configuration class.
*/
private void processInterfaces(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
for (SourceClass ifc : sourceClass.getInterfaces()) {
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(ifc);
for (MethodMetadata methodMetadata : beanMethods) {
if (!methodMetadata.isAbstract()) {
// A default method or other concrete method on a Java 8+ interface...
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
}
processInterfaces(configClass, ifc);
}
}

/**
* Retrieve the metadata for all <code>@Bean</code> methods.
*/
private Set<MethodMetadata> retrieveBeanMethodMetadata(SourceClass sourceClass) {
AnnotationMetadata original = sourceClass.getMetadata();
Set<MethodMetadata> beanMethods = original.getAnnotatedMethods(Bean.class.getName());
if (beanMethods.size() > 1 && original instanceof StandardAnnotationMetadata) {
// Try reading the class file via ASM for deterministic declaration order...
// Unfortunately, the JVM's standard reflection returns methods in arbitrary
// order, even between different runs of the same application on the same JVM.
try {
AnnotationMetadata asm =
this.metadataReaderFactory.getMetadataReader(original.getClassName()).getAnnotationMetadata();
Set<MethodMetadata> asmMethods = asm.getAnnotatedMethods(Bean.class.getName());
if (asmMethods.size() >= beanMethods.size()) {
Set<MethodMetadata> selectedMethods = new LinkedHashSet<>(asmMethods.size());
for (MethodMetadata asmMethod : asmMethods) {
for (MethodMetadata beanMethod : beanMethods) {
if (beanMethod.getMethodName().equals(asmMethod.getMethodName())) {
selectedMethods.add(beanMethod);
break;
}
}
}
if (selectedMethods.size() == beanMethods.size()) {
// All reflection-detected methods found in ASM method set -> proceed
beanMethods = selectedMethods;
}
}
}
catch (IOException ex) {
logger.debug("Failed to read class file via ASM for determining @Bean method order", ex);
// No worries, let's continue with the reflection metadata we started with...
}
}
return beanMethods;
}


/**
* Process the given <code>@PropertySource</code> annotation metadata.
* @param propertySource metadata for the <code>@PropertySource</code> annotation found
* @throws IOException if loading a property source failed
*/
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
String name = propertySource.getString("name");
if (!StringUtils.hasLength(name)) {
name = null;
}
String encoding = propertySource.getString("encoding");
if (!StringUtils.hasLength(encoding)) {
encoding = null;
}
String[] locations = propertySource.getStringArray("value");
Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

for (String location : locations) {
try {
String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
Resource resource = this.resourceLoader.getResource(resolvedLocation);
addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
}
catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
// Placeholders not resolvable or resource not found when trying to open it
if (ignoreResourceNotFound) {
if (logger.isInfoEnabled()) {
logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}

private void addPropertySource(PropertySource<?> propertySource) {
String name = propertySource.getName();
MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();

if (this.propertySourceNames.contains(name)) {
// We've already added a version, we need to extend it
PropertySource<?> existing = propertySources.get(name);
if (existing != null) {
PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
((ResourcePropertySource) propertySource).withResourceName() : propertySource);
if (existing instanceof CompositePropertySource) {
((CompositePropertySource) existing).addFirstPropertySource(newSource);
}
else {
if (existing instanceof ResourcePropertySource) {
existing = ((ResourcePropertySource) existing).withResourceName();
}
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(newSource);
composite.addPropertySource(existing);
propertySources.replace(name, composite);
}
return;
}
}

if (this.propertySourceNames.isEmpty()) {
propertySources.addLast(propertySource);
}
else {
String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
propertySources.addBefore(firstProcessed, propertySource);
}
this.propertySourceNames.add(name);
}


/**
* Returns {@code @Import} class, considering all meta-annotations.
*/
private Set<SourceClass> getImports(SourceClass sourceClass) throws IOException {
Set<SourceClass> imports = new LinkedHashSet<>();
Set<SourceClass> visited = new LinkedHashSet<>();
collectImports(sourceClass, imports, visited);
return imports;
}

/**
* Recursively collect all declared {@code @Import} values. Unlike most
* meta-annotations it is valid to have several {@code @Import}s declared with
* different values; the usual process of returning values from the first
* meta-annotation on a class is not sufficient.
* <p>For example, it is common for a {@code @Configuration} class to declare direct
* {@code @Import}s in addition to meta-imports originating from an {@code @Enable}
* annotation.
* @param sourceClass the class to search
* @param imports the imports collected so far
* @param visited used to track visited classes to prevent infinite recursion
* @throws IOException if there is any problem reading metadata from the named class
*/
private void collectImports(SourceClass sourceClass, Set<SourceClass> imports, Set<SourceClass> visited)
throws IOException {

if (visited.add(sourceClass)) {
for (SourceClass annotation : sourceClass.getAnnotations()) {
String annName = annotation.getMetadata().getClassName();
if (!annName.startsWith("java") && !annName.equals(Import.class.getName())) {
collectImports(annotation, imports, visited);
}
}
imports.addAll(sourceClass.getAnnotationAttributes(Import.class.getName(), "value"));
}
}



private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, boolean checkForCircularImports) {

if (importCandidates.isEmpty()) {
return;
}

if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
for (SourceClass candidate : importCandidates) {
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
Class<?> candidateClass = candidate.loadClass();
ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
ParserStrategyUtils.invokeAwareMethods(
selector, this.environment, this.resourceLoader, this.registry);
if (selector instanceof DeferredImportSelector) {
this.deferredImportSelectorHandler.handle(
configClass, (DeferredImportSelector) selector);
}
else {
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
processImports(configClass, currentSourceClass, importSourceClasses, false);
}
}
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
ParserStrategyUtils.invokeAwareMethods(
registrar, this.environment, this.resourceLoader, this.registry);
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass));
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}

private boolean isChainedImportOnStack(ConfigurationClass configClass) {
if (this.importStack.contains(configClass)) {
String configClassName = configClass.getMetadata().getClassName();
AnnotationMetadata importingClass = this.importStack.getImportingClassFor(configClassName);
while (importingClass != null) {
if (configClassName.equals(importingClass.getClassName())) {
return true;
}
importingClass = this.importStack.getImportingClassFor(importingClass.getClassName());
}
}
return false;
}

ImportRegistry getImportRegistry() {
return this.importStack;
}


/**
* Factory method to obtain a {@link SourceClass} from a {@link ConfigurationClass}.
*/
private SourceClass asSourceClass(ConfigurationClass configurationClass) throws IOException {
AnnotationMetadata metadata = configurationClass.getMetadata();
if (metadata instanceof StandardAnnotationMetadata) {
return asSourceClass(((StandardAnnotationMetadata) metadata).getIntrospectedClass());
}
return asSourceClass(metadata.getClassName());
}

/**
* Factory method to obtain a {@link SourceClass} from a {@link Class}.
*/
SourceClass asSourceClass(@Nullable Class<?> classType) throws IOException {
if (classType == null) {
return new SourceClass(Object.class);
}
try {
// Sanity test that we can reflectively read annotations,
// including Class attributes; if not -> fall back to ASM
for (Annotation ann : classType.getAnnotations()) {
AnnotationUtils.validateAnnotation(ann);
}
return new SourceClass(classType);
}
catch (Throwable ex) {
// Enforce ASM via class name resolution
return asSourceClass(classType.getName());
}
}

/**
* Factory method to obtain {@link SourceClass SourceClasss} from class names.
*/
private Collection<SourceClass> asSourceClasses(String... classNames) throws IOException {
List<SourceClass> annotatedClasses = new ArrayList<>(classNames.length);
for (String className : classNames) {
annotatedClasses.add(asSourceClass(className));
}
return annotatedClasses;
}

/**
* Factory method to obtain a {@link SourceClass} from a class name.
*/
SourceClass asSourceClass(@Nullable String className) throws IOException {
if (className == null) {
return new SourceClass(Object.class);
}
if (className.startsWith("java")) {
// Never use ASM for core java types
try {
return new SourceClass(ClassUtils.forName(className, this.resourceLoader.getClassLoader()));
}
catch (ClassNotFoundException ex) {
throw new NestedIOException("Failed to load class [" + className + "]", ex);
}
}
return new SourceClass(this.metadataReaderFactory.getMetadataReader(className));
}


@SuppressWarnings("serial")
private static class ImportStack extends ArrayDeque<ConfigurationClass> implements ImportRegistry {

private final MultiValueMap<String, AnnotationMetadata> imports = new LinkedMultiValueMap<>();

public void registerImport(AnnotationMetadata importingClass, String importedClass) {
this.imports.add(importedClass, importingClass);
}

@Override
@Nullable
public AnnotationMetadata getImportingClassFor(String importedClass) {
return CollectionUtils.lastElement(this.imports.get(importedClass));
}

@Override
public void removeImportingClass(String importingClass) {
for (List<AnnotationMetadata> list : this.imports.values()) {
for (Iterator<AnnotationMetadata> iterator = list.iterator(); iterator.hasNext();) {
if (iterator.next().getClassName().equals(importingClass)) {
iterator.remove();
break;
}
}
}
}

/**
* Given a stack containing (in order)
* <ul>
* <li>com.acme.Foo</li>
* <li>com.acme.Bar</li>
* <li>com.acme.Baz</li>
* </ul>
* return "[Foo->Bar->Baz]".
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
Iterator<ConfigurationClass> iterator = iterator();
while (iterator.hasNext()) {
builder.append(iterator.next().getSimpleName());
if (iterator.hasNext()) {
builder.append("->");
}
}
return builder.append(']').toString();
}
}


private class DeferredImportSelectorHandler {

@Nullable
private List<DeferredImportSelectorHolder> deferredImportSelectors = new ArrayList<>();

/**
* Handle the specified {@link DeferredImportSelector}. If deferred import
* selectors are being collected, this registers this instance to the list. If
* they are being processed, the {@link DeferredImportSelector} is also processed
* immediately according to its {@link DeferredImportSelector.Group}.
* @param configClass the source configuration class
* @param importSelector the selector to handle
*/
public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(
configClass, importSelector);
if (this.deferredImportSelectors == null) {
DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
handler.register(holder);
handler.processGroupImports();
}
else {
this.deferredImportSelectors.add(holder);
}
}

public void process() {
List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
this.deferredImportSelectors = null;
try {
if (deferredImports != null) {
DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
deferredImports.forEach(handler::register);
handler.processGroupImports();
}
}
finally {
this.deferredImportSelectors = new ArrayList<>();
}
}

}


private class DeferredImportSelectorGroupingHandler {

private final Map<Object, DeferredImportSelectorGrouping> groupings = new LinkedHashMap<>();

private final Map<AnnotationMetadata, ConfigurationClass> configurationClasses = new HashMap<>();

public void register(DeferredImportSelectorHolder deferredImport) {
Class<? extends Group> group = deferredImport.getImportSelector()
.getImportGroup();
DeferredImportSelectorGrouping grouping = this.groupings.computeIfAbsent(
(group != null ? group : deferredImport),
key -> new DeferredImportSelectorGrouping(createGroup(group)));
grouping.add(deferredImport);
this.configurationClasses.put(deferredImport.getConfigurationClass().getMetadata(),
deferredImport.getConfigurationClass());
}

public void processGroupImports() {
for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
grouping.getImports().forEach(entry -> {
ConfigurationClass configurationClass = this.configurationClasses.get(
entry.getMetadata());
try {
processImports(configurationClass, asSourceClass(configurationClass),
asSourceClasses(entry.getImportClassName()), false);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configurationClass.getMetadata().getClassName() + "]", ex);
}
});
}
}

private Group createGroup(@Nullable Class<? extends Group> type) {
Class<? extends Group> effectiveType = (type != null ? type
: DefaultDeferredImportSelectorGroup.class);
Group group = BeanUtils.instantiateClass(effectiveType);
ParserStrategyUtils.invokeAwareMethods(group,
ConfigurationClassParser.this.environment,
ConfigurationClassParser.this.resourceLoader,
ConfigurationClassParser.this.registry);
return group;
}

}


private static class DeferredImportSelectorHolder {

private final ConfigurationClass configurationClass;

private final DeferredImportSelector importSelector;

public DeferredImportSelectorHolder(ConfigurationClass configClass, DeferredImportSelector selector) {
this.configurationClass = configClass;
this.importSelector = selector;
}

public ConfigurationClass getConfigurationClass() {
return this.configurationClass;
}

public DeferredImportSelector getImportSelector() {
return this.importSelector;
}
}


private static class DeferredImportSelectorGrouping {

private final DeferredImportSelector.Group group;

private final List<DeferredImportSelectorHolder> deferredImports = new ArrayList<>();

DeferredImportSelectorGrouping(Group group) {
this.group = group;
}

public void add(DeferredImportSelectorHolder deferredImport) {
this.deferredImports.add(deferredImport);
}

/**
* Return the imports defined by the group.
* @return each import with its associated configuration class
*/
public Iterable<Group.Entry> getImports() {
for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
this.group.process(deferredImport.getConfigurationClass().getMetadata(),
deferredImport.getImportSelector());
}
return this.group.selectImports();
}
}


private static class DefaultDeferredImportSelectorGroup implements Group {

private final List<Entry> imports = new ArrayList<>();

@Override
public void process(AnnotationMetadata metadata, DeferredImportSelector selector) {
for (String importClassName : selector.selectImports(metadata)) {
this.imports.add(new Entry(metadata, importClassName));
}
}

@Override
public Iterable<Entry> selectImports() {
return this.imports;
}
}


/**
* 简单的封装器,允许以统一的方式处理带有注解的类,不论他们是如何加载的。
*/
private class SourceClass implements Ordered {

private final Object source; // Class or MetadataReader

private final AnnotationMetadata metadata;

public SourceClass(Object source) {
this.source = source;
if (source instanceof Class) {
this.metadata = new StandardAnnotationMetadata((Class<?>) source, true);
}
else {
this.metadata = ((MetadataReader) source).getAnnotationMetadata();
}
}

public final AnnotationMetadata getMetadata() {
return this.metadata;
}

@Override
public int getOrder() {
Integer order = ConfigurationClassUtils.getOrder(this.metadata);
return (order != null ? order : Ordered.LOWEST_PRECEDENCE);
}

public Class<?> loadClass() throws ClassNotFoundException {
if (this.source instanceof Class) {
return (Class<?>) this.source;
}
String className = ((MetadataReader) this.source).getClassMetadata().getClassName();
return ClassUtils.forName(className, resourceLoader.getClassLoader());
}

public boolean isAssignable(Class<?> clazz) throws IOException {
if (this.source instanceof Class) {
return clazz.isAssignableFrom((Class<?>) this.source);
}
return new AssignableTypeFilter(clazz).match((MetadataReader) this.source, metadataReaderFactory);
}

public ConfigurationClass asConfigClass(ConfigurationClass importedBy) throws IOException {
if (this.source instanceof Class) {
return new ConfigurationClass((Class<?>) this.source, importedBy);
}
return new ConfigurationClass((MetadataReader) this.source, importedBy);
}

public Collection<SourceClass> getMemberClasses() throws IOException {
Object sourceToProcess = this.source;
if (sourceToProcess instanceof Class) {
Class<?> sourceClass = (Class<?>) sourceToProcess;
try {
Class<?>[] declaredClasses = sourceClass.getDeclaredClasses();
List<SourceClass> members = new ArrayList<>(declaredClasses.length);
for (Class<?> declaredClass : declaredClasses) {
members.add(asSourceClass(declaredClass));
}
return members;
}
catch (NoClassDefFoundError err) {
// getDeclaredClasses() failed because of non-resolvable dependencies
// -> fall back to ASM below
sourceToProcess = metadataReaderFactory.getMetadataReader(sourceClass.getName());
}
}

// ASM-based resolution - safe for non-resolvable classes as well
MetadataReader sourceReader = (MetadataReader) sourceToProcess;
String[] memberClassNames = sourceReader.getClassMetadata().getMemberClassNames();
List<SourceClass> members = new ArrayList<>(memberClassNames.length);
for (String memberClassName : memberClassNames) {
try {
members.add(asSourceClass(memberClassName));
}
catch (IOException ex) {
// Let's skip it if it's not resolvable - we're just looking for candidates
if (logger.isDebugEnabled()) {
logger.debug("Failed to resolve member class [" + memberClassName +
"] - not considering it as a configuration class candidate");
}
}
}
return members;
}

public SourceClass getSuperClass() throws IOException {
if (this.source instanceof Class) {
return asSourceClass(((Class<?>) this.source).getSuperclass());
}
return asSourceClass(((MetadataReader) this.source).getClassMetadata().getSuperClassName());
}

public Set<SourceClass> getInterfaces() throws IOException {
Set<SourceClass> result = new LinkedHashSet<>();
if (this.source instanceof Class) {
Class<?> sourceClass = (Class<?>) this.source;
for (Class<?> ifcClass : sourceClass.getInterfaces()) {
result.add(asSourceClass(ifcClass));
}
}
else {
for (String className : this.metadata.getInterfaceNames()) {
result.add(asSourceClass(className));
}
}
return result;
}

public Set<SourceClass> getAnnotations() throws IOException {
Set<SourceClass> result = new LinkedHashSet<>();
for (String className : this.metadata.getAnnotationTypes()) {
try {
result.add(getRelated(className));
}
catch (Throwable ex) {
// An annotation not present on the classpath is being ignored
// by the JVM's class loading -> ignore here as well.
}
}
return result;
}

public Collection<SourceClass> getAnnotationAttributes(String annType, String attribute) throws IOException {
Map<String, Object> annotationAttributes = this.metadata.getAnnotationAttributes(annType, true);
if (annotationAttributes == null || !annotationAttributes.containsKey(attribute)) {
return Collections.emptySet();
}
String[] classNames = (String[]) annotationAttributes.get(attribute);
Set<SourceClass> result = new LinkedHashSet<>();
for (String className : classNames) {
result.add(getRelated(className));
}
return result;
}

private SourceClass getRelated(String className) throws IOException {
if (this.source instanceof Class) {
try {
Class<?> clazz = ClassUtils.forName(className, ((Class<?>) this.source).getClassLoader());
return asSourceClass(clazz);
}
catch (ClassNotFoundException ex) {
// Ignore -> fall back to ASM next, except for core java types.
if (className.startsWith("java")) {
throw new NestedIOException("Failed to load class [" + className + "]", ex);
}
return new SourceClass(metadataReaderFactory.getMetadataReader(className));
}
}
return asSourceClass(className);
}

@Override
public boolean equals(Object other) {
return (this == other || (other instanceof SourceClass &&
this.metadata.getClassName().equals(((SourceClass) other).metadata.getClassName())));
}

@Override
public int hashCode() {
return this.metadata.getClassName().hashCode();
}

@Override
public String toString() {
return this.metadata.getClassName();
}
}


/**
* {@link Problem} registered upon detection of a circular {@link Import}.
*/
private static class CircularImportProblem extends Problem {

public CircularImportProblem(ConfigurationClass attemptedImport, Deque<ConfigurationClass> importStack) {
super(String.format("A circular @Import has been detected: " +
"Illegal attempt by @Configuration class '%s' to import class '%s' as '%s' is " +
"already present in the current import stack %s", importStack.element().getSimpleName(),
attemptedImport.getSimpleName(), attemptedImport.getSimpleName(), importStack),
new Location(importStack.element().getResource(), attemptedImport.getMetadata()));
}
}

}

ComponentScanAnnotationParser

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/**
* @ComponentScan 的解析器
*
* @author Chris Beams
* @author Juergen Hoeller
* @author Sam Brannen
* @since 3.1
* @see ClassPathBeanDefinitionScanner#scan(String...)
* @see ComponentScanBeanDefinitionParser
*/
class ComponentScanAnnotationParser {

private final Environment environment;

private final ResourceLoader resourceLoader;

private final BeanNameGenerator beanNameGenerator;

private final BeanDefinitionRegistry registry;


public ComponentScanAnnotationParser(Environment environment, ResourceLoader resourceLoader,
BeanNameGenerator beanNameGenerator, BeanDefinitionRegistry registry) {

this.environment = environment;
this.resourceLoader = resourceLoader;
this.beanNameGenerator = beanNameGenerator;
this.registry = registry;
}


public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
// 初始化 ClassPathBeanDefinitionScanner
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

// 获取名称创建器
Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
BeanUtils.instantiateClass(generatorClass));

// 设置作用域代理类
ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
scanner.setScopedProxyMode(scopedProxyMode);
}
else {
Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
}

// 设置资源名称表达式
scanner.setResourcePattern(componentScan.getString("resourcePattern"));

// 获取包含过滤器
for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter)) {
scanner.addIncludeFilter(typeFilter);
}
}
// 获取排除过滤器
for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter)) {
scanner.addExcludeFilter(typeFilter);
}
}

// 设置是否懒加载
boolean lazyInit = componentScan.getBoolean("lazyInit");
if (lazyInit) {
scanner.getBeanDefinitionDefaults().setLazyInit(true);
}

// 声明扫描包路径
Set<String> basePackages = new LinkedHashSet<>();
// 获取注解中声明的扫描包路径
String[] basePackagesArray = componentScan.getStringArray("basePackages");
for (String pkg : basePackagesArray) {
String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
Collections.addAll(basePackages, tokenized);
}
for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
basePackages.add(ClassUtils.getPackageName(clazz));
}
// 如果扫描包路径为空,则扫描当前类所在的包
if (basePackages.isEmpty()) {
basePackages.add(ClassUtils.getPackageName(declaringClass));
}

// 添加过滤器
scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
@Override
protected boolean matchClassName(String className) {
return declaringClass.equals(className);
}
});
// 调用 ClassPathBeanDefinitionScanner 的 doScan 方法
return scanner.doScan(StringUtils.toStringArray(basePackages));
}

private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {
List<TypeFilter> typeFilters = new ArrayList<>();
FilterType filterType = filterAttributes.getEnum("type");

for (Class<?> filterClass : filterAttributes.getClassArray("classes")) {
switch (filterType) {
case ANNOTATION:
Assert.isAssignable(Annotation.class, filterClass,
"@ComponentScan ANNOTATION type filter requires an annotation type");
@SuppressWarnings("unchecked")
Class<Annotation> annotationType = (Class<Annotation>) filterClass;
typeFilters.add(new AnnotationTypeFilter(annotationType));
break;
case ASSIGNABLE_TYPE:
typeFilters.add(new AssignableTypeFilter(filterClass));
break;
case CUSTOM:
Assert.isAssignable(TypeFilter.class, filterClass,
"@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
ParserStrategyUtils.invokeAwareMethods(
filter, this.environment, this.resourceLoader, this.registry);
typeFilters.add(filter);
break;
default:
throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType);
}
}

for (String expression : filterAttributes.getStringArray("pattern")) {
switch (filterType) {
case ASPECTJ:
typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
break;
case REGEX:
typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
break;
default:
throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
}
}

return typeFilters;
}

}

ClassPathBeanDefinitionScanner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/**
* bean 定义扫描器,检测类路径下的候选 bean,并将其对应的的 bean 定义注册到给定的注册中心。
* 通过可以配置的类型过滤器筛选类。默认的类型过滤器是 Spring 的注解:
* @Component@Repository@Service@Controller,同样支持 @Javax.annotation.ManagedBean
* 和 @Javax.inject.Named,如果支持的话。
*
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
* @since 2.5
* @see AnnotationConfigApplicationContext#scan
* @see org.springframework.stereotype.Component
* @see org.springframework.stereotype.Repository
* @see org.springframework.stereotype.Service
* @see org.springframework.stereotype.Controller
*/
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {

private final BeanDefinitionRegistry registry;

private BeanDefinitionDefaults beanDefinitionDefaults = new BeanDefinitionDefaults();

@Nullable
private String[] autowireCandidatePatterns;

private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();

private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();

private boolean includeAnnotationConfig = true;


/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
this(registry, true);
}

/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.
* <p>If the passed-in bean factory does not only implement the
* {@code BeanDefinitionRegistry} interface but also the {@code ResourceLoader}
* interface, it will be used as default {@code ResourceLoader} as well. This will
* usually be the case for {@link org.springframework.context.ApplicationContext}
* implementations.
* <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}
* will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
* <p>If the passed-in bean factory also implements {@link EnvironmentCapable} its
* environment will be used by this reader. Otherwise, the reader will initialize and
* use a {@link org.springframework.core.env.StandardEnvironment}. All
* {@code ApplicationContext} implementations are {@code EnvironmentCapable}, while
* normal {@code BeanFactory} implementations are not.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
* @param useDefaultFilters whether to include the default filters for the
* {@link org.springframework.stereotype.Component @Component},
* {@link org.springframework.stereotype.Repository @Repository},
* {@link org.springframework.stereotype.Service @Service}, and
* {@link org.springframework.stereotype.Controller @Controller} stereotype annotations
* @see #setResourceLoader
* @see #setEnvironment
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
}

/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and
* using the given {@link Environment} when evaluating bean definition profile metadata.
* <p>If the passed-in bean factory does not only implement the {@code
* BeanDefinitionRegistry} interface but also the {@link ResourceLoader} interface, it
* will be used as default {@code ResourceLoader} as well. This will usually be the
* case for {@link org.springframework.context.ApplicationContext} implementations.
* <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}
* will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
* @param useDefaultFilters whether to include the default filters for the
* {@link org.springframework.stereotype.Component @Component},
* {@link org.springframework.stereotype.Repository @Repository},
* {@link org.springframework.stereotype.Service @Service}, and
* {@link org.springframework.stereotype.Controller @Controller} stereotype annotations
* @param environment the Spring {@link Environment} to use when evaluating bean
* definition profile metadata
* @since 3.1
* @see #setResourceLoader
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment) {

this(registry, useDefaultFilters, environment,
(registry instanceof ResourceLoader ? (ResourceLoader) registry : null));
}

/**
* Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and
* using the given {@link Environment} when evaluating bean definition profile metadata.
* @param registry the {@code BeanFactory} to load bean definitions into, in the form
* of a {@code BeanDefinitionRegistry}
* @param useDefaultFilters whether to include the default filters for the
* {@link org.springframework.stereotype.Component @Component},
* {@link org.springframework.stereotype.Repository @Repository},
* {@link org.springframework.stereotype.Service @Service}, and
* {@link org.springframework.stereotype.Controller @Controller} stereotype annotations
* @param environment the Spring {@link Environment} to use when evaluating bean
* definition profile metadata
* @param resourceLoader the {@link ResourceLoader} to use
* @since 4.3.6
*/
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, @Nullable ResourceLoader resourceLoader) {

Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;

if (useDefaultFilters) {
registerDefaultFilters();
}
setEnvironment(environment);
setResourceLoader(resourceLoader);
}


/**
* Return the BeanDefinitionRegistry that this scanner operates on.
*/
@Override
public final BeanDefinitionRegistry getRegistry() {
return this.registry;
}

/**
* Set the defaults to use for detected beans.
* @see BeanDefinitionDefaults
*/
public void setBeanDefinitionDefaults(@Nullable BeanDefinitionDefaults beanDefinitionDefaults) {
this.beanDefinitionDefaults =
(beanDefinitionDefaults != null ? beanDefinitionDefaults : new BeanDefinitionDefaults());
}

/**
* Return the defaults to use for detected beans (never {@code null}).
* @since 4.1
*/
public BeanDefinitionDefaults getBeanDefinitionDefaults() {
return this.beanDefinitionDefaults;
}

/**
* Set the name-matching patterns for determining autowire candidates.
* @param autowireCandidatePatterns the patterns to match against
*/
public void setAutowireCandidatePatterns(@Nullable String... autowireCandidatePatterns) {
this.autowireCandidatePatterns = autowireCandidatePatterns;
}

/**
* Set the BeanNameGenerator to use for detected bean classes.
* <p>Default is a {@link AnnotationBeanNameGenerator}.
*/
public void setBeanNameGenerator(@Nullable BeanNameGenerator beanNameGenerator) {
this.beanNameGenerator = (beanNameGenerator != null ? beanNameGenerator : new AnnotationBeanNameGenerator());
}

/**
* Set the ScopeMetadataResolver to use for detected bean classes.
* Note that this will override any custom "scopedProxyMode" setting.
* <p>The default is an {@link AnnotationScopeMetadataResolver}.
* @see #setScopedProxyMode
*/
public void setScopeMetadataResolver(@Nullable ScopeMetadataResolver scopeMetadataResolver) {
this.scopeMetadataResolver =
(scopeMetadataResolver != null ? scopeMetadataResolver : new AnnotationScopeMetadataResolver());
}

/**
* Specify the proxy behavior for non-singleton scoped beans.
* Note that this will override any custom "scopeMetadataResolver" setting.
* <p>The default is {@link ScopedProxyMode#NO}.
* @see #setScopeMetadataResolver
*/
public void setScopedProxyMode(ScopedProxyMode scopedProxyMode) {
this.scopeMetadataResolver = new AnnotationScopeMetadataResolver(scopedProxyMode);
}

/**
* Specify whether to register annotation config post-processors.
* <p>The default is to register the post-processors. Turn this off
* to be able to ignore the annotations or to process them differently.
*/
public void setIncludeAnnotationConfig(boolean includeAnnotationConfig) {
this.includeAnnotationConfig = includeAnnotationConfig;
}


/**
* Perform a scan within the specified base packages.
* @param basePackages the packages to check for annotated classes
* @return number of beans registered
*/
public int scan(String... basePackages) {
int beanCountAtScanStart = this.registry.getBeanDefinitionCount();

doScan(basePackages);

// Register annotation config processors, if necessary.
if (this.includeAnnotationConfig) {
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}

return (this.registry.getBeanDefinitionCount() - beanCountAtScanStart);
}

/**
* 扫描给定的包路径,返回已注册的 bean 定义。该方法不会注册注解配置处理器,而是留给了调用者。
* @param basePackages the packages to check for annotated classes
* @return set of beans registered if any for tooling registration purposes (never {@code null})
*/
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
// 已注册的 bean 定义
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
// 扫描包路径下的 bean 定义
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
// 遍历 bean 定义
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}

/**
* Apply further settings to the given bean definition,
* beyond the contents retrieved from scanning the component class.
* @param beanDefinition the scanned bean definition
* @param beanName the generated bean name for the given bean
*/
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
beanDefinition.applyDefaults(this.beanDefinitionDefaults);
if (this.autowireCandidatePatterns != null) {
beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
}
}

/**
* Register the specified bean with the given registry.
* <p>Can be overridden in subclasses, e.g. to adapt the registration
* process or to register further bean definitions for each scanned bean.
* @param definitionHolder the bean definition plus bean name for the bean
* @param registry the BeanDefinitionRegistry to register the bean with
*/
protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) {
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);
}


/**
* Check the given candidate's bean name, determining whether the corresponding
* bean definition needs to be registered or conflicts with an existing definition.
* @param beanName the suggested name for the bean
* @param beanDefinition the corresponding bean definition
* @return {@code true} if the bean can be registered as-is;
* {@code false} if it should be skipped because there is an
* existing, compatible bean definition for the specified name
* @throws ConflictingBeanDefinitionException if an existing, incompatible
* bean definition has been found for the specified name
*/
protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
if (!this.registry.containsBeanDefinition(beanName)) {
return true;
}
BeanDefinition existingDef = this.registry.getBeanDefinition(beanName);
BeanDefinition originatingDef = existingDef.getOriginatingBeanDefinition();
if (originatingDef != null) {
existingDef = originatingDef;
}
if (isCompatible(beanDefinition, existingDef)) {
return false;
}
throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName +
"' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " +
"non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");
}

/**
* Determine whether the given new bean definition is compatible with
* the given existing bean definition.
* <p>The default implementation considers them as compatible when the existing
* bean definition comes from the same source or from a non-scanning source.
* @param newDefinition the new bean definition, originated from scanning
* @param existingDefinition the existing bean definition, potentially an
* explicitly defined one or a previously generated one from scanning
* @return whether the definitions are considered as compatible, with the
* new definition to be skipped in favor of the existing definition
*/
protected boolean isCompatible(BeanDefinition newDefinition, BeanDefinition existingDefinition) {
return (!(existingDefinition instanceof ScannedGenericBeanDefinition) || // explicitly registered overriding bean
(newDefinition.getSource() != null && newDefinition.getSource().equals(existingDefinition.getSource())) || // scanned same file twice
newDefinition.equals(existingDefinition)); // scanned equivalent class twice
}


/**
* Get the Environment from the given registry if possible, otherwise return a new
* StandardEnvironment.
*/
private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry instanceof EnvironmentCapable) {
return ((EnvironmentCapable) registry).getEnvironment();
}
return new StandardEnvironment();
}

}

实例化 bean

实例化所有 bean 是在最后完成 BeanFactory 初始化时,在 AnnotationConfigServletWebServerApplicationContext 的 finishBeanFactoryInitialization 方法中调用了 BeanFactory 的 preInstantiateSingletons 方法完成的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* 完成上下文 bean 工厂的初始化,以及初始化所有剩余的单例 bean
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 初始化上下文的转换服务
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));
}

// 设置占位符解析器
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}

// 尽早初始化 LoadTimeWeaverAware bean 以允许尽早注册其变换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}

// 停止使用临时 ClassLoader 进行类型匹配
beanFactory.setTempClassLoader(null);

// 允许缓存所有的 bean 定义元数据,不希望再次改变
beanFactory.freezeConfiguration();

// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有剩余的单例(非懒加载的)
beanFactory.preInstantiateSingletons();
}

Bean 实例化整体逻辑大概如下图:

Bean 实例化流程

遍历所有 bean 名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {

@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}

// 遍历一个副本以允许这些初始化方法可以注册新的 bean 定义。
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

// 触发所有非懒加载单例 bean 的初始化
for (String beanName : beanNames) {
// 获取完整 bean 定义
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 进行校验,非抽象且非懒加载的单例
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 通过 beanName 校验是否是一个 factoryBean
if (isFactoryBean(beanName)) {
// 获取 factoryBean 实例
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) {
// 加载 bean
getBean(beanName);
}
}
}
// 如果不是 factoryBean 则调用 getBean 方法初始化
else {
getBean(beanName);
}
}
}

// 为所有适用的单例 bean 进行初始化后处理
for (String beanName : beanNames) {
// 获取单例
Object singletonInstance = getSingleton(beanName);
// 校验类型
if (singletonInstance instanceof SmartInitializingSingleton) {
// 类型转换
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
// 执行 afterSingletonsInstantiated 方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}

}

获取 Bean 实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {


/**
* 通过 bean 名称查询一个 bean
*/
@Override
public Object getBean(String name) throws BeansException {
// 调用具体实现方法
return doGetBean(name, null, null, false);
}

/**
* 获取 bean 的实现方法
*/
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

// 得到 bean 的规范名称
final String beanName = transformedBeanName(name);
Object bean;

// 为手动注册的单例提前查询单例缓存
Object sharedInstance = getSingleton(beanName);
// 如果查询到且入参 args 为空
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 如果不存在
else {
// 校验当前线程是否正在创建当前 bean
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}

BeanFactory parentBeanFactory = getParentBeanFactory();
// 如果当前工厂不存在给定名称的 bean 定义,则查询父工厂
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// bean 的真是名称
String nameToLookup = originalBeanName(name);
// 如果父工厂是 AbstractBeanFactory 则还是调用 doGetBean 方法
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// 将期望参数一起委托给父工厂
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// 没有参数则委托给标准的 getBean 方法
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
// 其他情况只通过 beanName 查询
return (T) parentBeanFactory.getBean(nameToLookup);
}
}

// 是否标记为创建中状态
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}

try {
// 获取 bean 定义
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 校验 bean 定义
checkMergedBeanDefinition(mbd, beanName, args);

// 获取依赖的 bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
// 先初始化依赖的 bean
for (String dep : dependsOn) {
// 校验是否有循环依赖
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 注册依赖关系
registerDependentBean(dep, beanName);
try {
// 初始化依赖的 bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}

// 是否为单例
if (mbd.isSingleton()) {
// 获取单例,不存在则创建
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
// 获取 bean 实例
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 原型模式
else if (mbd.isPrototype()) {
// 直接创建新的 bean 实例
Object prototypeInstance = null;
try {
// 原型 bean 创建前回调方法
beforePrototypeCreation(beanName);
// 床架 bean 实例
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
// 原型 bean 创建后回调
afterPrototypeCreation(beanName);
}
// 获取 bean 实例
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 其他作用域
else {
String scopeName = mbd.getScope();
// 获取作用域
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
// 从作用域中获取 bean
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
// 清除 bean 创建状态
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}

// 校验期望类型是否与实际 bean 实例类型匹配
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
// 必要时进行类型转换
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
// 转换后实例为空抛出异常
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
// 返回 bean 实例
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
// 返回 bean 实例
return (T) bean;
}

/**
* 获取给定 bean 实例暴露的对象,bean 实例它自己或它创建的一个对象如果是 FactoryBean 的话。
* @param beanInstance 单例 bean 实例
* @param name name 可能带有 & 前缀
* @param beanName 规范 bean 名称
* @param mbd 合并的 bean 定义
* @return 要为 bean 公开的对象
*/
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

// 如果 name 带有 & 前缀,则表示 beanInstance 是一个 FactoryBean
if (BeanFactoryUtils.isFactoryDereference(name)) {
// 如果是空对象则直接返回
if (beanInstance instanceof NullBean) {
return beanInstance;
}
// 带有 & 前缀但是非 FactoryBean 则直接抛出异常
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
}

// 非 FactoryBean 或者待有 & 前缀的直接放回 beanInstance
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}

/*
* 走到这里只有一种情况,即 name 没有 & 前缀且 beanInstance 继承自 FactoryBean
*/
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
}

获取单例 bean 实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {

/**
* 返回给定名称下已注册的原始单例对象,如果至今没有注册则创建并注册一个新的
* @param beanName bean 名称
* @param singletonFactory 必要时创建单例的对象工厂
* @return 已注册的单例
*/
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 同 bean 名称查询单例对象
Object singletonObject = this.singletonObjects.get(beanName);
// 如果为空
if (singletonObject == null) {
// 当前正在进行摧毁单例,则抛出异常
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 单例 bean 创建之前的回调(添加 beanName 到正在创建的 bean 的名称集合中)
beforeSingletonCreation(beanName);

boolean newSingleton = false;
// 是否需要记录被抑制的异常
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
// 初始化被抑制的异常列表
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 通过对象工厂创建对象
singletonObject = singletonFactory.getObject();
// 设置为新的单例对象
newSingleton = true;
}
catch (IllegalStateException ex) {
// 校验 beanName 是否被隐式创建,如果是则继续执行,否则抛出异常
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
// 记录失败相关异常
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
// 抛出异常
throw ex;
}
finally {
// 恢复抑制异常列表
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 创建 bean 之后的回调
afterSingletonCreation(beanName);
}
// 如果是新创建的单例对象,添加到单例对象缓存中
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
// 返回单例对象
return singletonObject;
}
}

}

创建 Bean 实例

整体逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {

/**
* 创建 bean 实例
*/
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
// 复制 bean 定义
RootBeanDefinition mbdToUse = mbd;

// 解析 bean 的 class 对象
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
// 校验 bean 定义,创建新的 RootBeanDefinition,设置解析后的 class 对象
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

// 准备方法重写
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// 给 BeanPostProcessor 一个机会返回一个目标 bean 实例的代理实例
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 如果 bean 实例不为空则直接返回
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}

try {
// 创建 bean 实例
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
// 返回结果
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

/**
* 创建 bean 实例逻辑
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {

// 封装目标 bean 的 bean 实例
BeanWrapper instanceWrapper = null;
// 如果是单例 bean,则把封装 bean 从缓存中移除
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 如果封装 bean 实例为空则创建一个封装 bean
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 获取目标 bean 实例
final Object bean = instanceWrapper.getWrappedInstance();
// 目标 bean 的 class 对象
Class<?> beanType = instanceWrapper.getWrappedClass();
// 设置 bean 定义的 resolvedTargetType
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 执行所有的 MergedBeanDefinitionPostProcessor,此时其中一个实现 AutowiredAnnotationBeanPostProcessor
// 会解析所有的 bean 定义,记录他们需要注入的 bean
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
// 标记 bean 定义已被后处理器处理过
mbd.postProcessed = true;
}
}


boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 添加 bean factoryBean 解决循环依赖问题
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// 最终返回的 bean 实例
Object exposedObject = bean;
try {
// 解析 bean 依赖,并注入 bean
populateBean(beanName, mbd, instanceWrapper);
// 调用 bean 相关初始化方法
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}

// 如果处于创建期
if (earlySingletonExposure) {
// 从单例 Map 中获取单例 bean
Object earlySingletonReference = getSingleton(beanName, false);
// 该 bean 已创建
if (earlySingletonReference != null) {
// 如果 exposedObject 没有被修改
if (exposedObject == bean) {
// 则将 exposedObject 设置为已创建的实例
exposedObject = earlySingletonReference;
}
// 更新 bean 依赖
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}

// 注册为 DisposableBean 如果必要的话
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

// 返回 bean 实例
return exposedObject;
}

/**
* 创建目标 bean 的封装 bean
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 解析 bean 的 class 对象
Class<?> beanClass = resolveBeanClass(mbd, beanName);

// 校验
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}

// 如果实例提供器不为空 则从 bean 提供器中获取 bean 实例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

// 如果工厂名不为空,则使用命名的工厂方法实例化 bean
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}


boolean resolved = false;
boolean autowireNecessary = false;
// 如果参数为空
if (args == null) {
// 加锁
synchronized (mbd.constructorArgumentLock) {
// 如果已解析的构造函数或者工厂方法不为空
if (mbd.resolvedConstructorOrFactoryMethod != null) {
// 更新标志位
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 如果构造函数已解析或者工厂方法不为空
if (resolved) {
// 如果构造函数已解析则直接使用构造函数实例化
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
// 否则使用默认的无参构造函数
else {
return instantiateBean(beanName, mbd);
}
}

// 确定可以用来装配的构造函数,当前使用 AbstractAutowireCapableBeanFactory
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 勾选构造函数不为空或者装配模式为构造函数装配或者构造函数参数不为空或者给定参数不为空
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 使用构造函数创建
return autowireConstructor(beanName, mbd, ctors, args);
}

// 使用首选构造函数作为默认的构造函数?目前该方法只会返回 null
ctors = mbd.getPreferredConstructors();
// 如果不为空,使用该构造函数实例化
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}

// 没有特殊处理,则使用无参构造函数。
return instantiateBean(beanName, mbd);
}

/**
* 解析 bean 依赖,并注入 bean
*
*/
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 参数校验
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}

// 给任意的 InstantiationAwareBeanPostProcessor 机会在 bean 属性被设置值之前去修改 bean
// 的状态。例如,这样可以用于字段方式的注入
boolean continueWithPropertyPopulation = true;

// 非 synthetic 的(应用程序自己定义的 bean)并且存在 InstantiationAwareBeanPostProcessor
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 遍历所有 BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 判断是否为 InstantiationAwareBeanPostProcessor 类型
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 类型转换,执行 postProcessAfterInstantiation 方法
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
// 执行完成任意一个,标记 continueWithPropertyPopulation,并跳出循环
continueWithPropertyPopulation = false;
break;
}
}
}
}

// 如果有被任意的 InstantiationAwareBeanPostProcessor 处理过 bean 定义,则结束方法
if (!continueWithPropertyPopulation) {
return;
}

// bean 定义的属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

// 判断装配类型,并根据不同的装配类型进行装配
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
// 重新赋值
pvs = newPvs;
}

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 是否校验 bean 依赖的标识位
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

PropertyDescriptor[] filteredPds = null;
// 同样判断是否存在 InstantiationAwareBeanPostProcessor
if (hasInstAwareBpps) {
// 如果属性为空则重新获取 bean 属性
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
// 遍历 BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 判断类型
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 类型转换
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 执行 postProcessProperties 方法,其中 AutowiredAnnotationBeanPostProcessor 在执行 postProcessProperties 时会
// 会取得之前解析完成的 bean 依赖,并将其注入进去。
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}

// 是否需要校验 bean 依赖
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}

// 处理 bean 属性值
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

/**
* 调用 bean 相关的初始化方法
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 权限校验,调用相关 Aware 接口实现
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
// 调用所有 BeanPostProcessor 的 postProcessBeforeInitialization 方法
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
// 调用 bean 的初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 调用所有 BeanPostProcessor 的 applyBeanPostProcessorsAfterInitialization 方法
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

// 返回结果
return wrappedBean;
}

}

解析 bean 依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {

/**
* 处理 bean 定义,解析 bean 依赖
*/
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
// 解析 bean 依赖
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
// 校验配置
metadata.checkConfigMembers(beanDefinition);
}

/**
* 查询 bean 依赖
*/
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// 将类名当做缓存的 key
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// 首先快速校验缓存 map,使用最小返回的锁
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
// 如果满足其中任一条件就需要重新解析,metadata 为空或者注入的的目标 class 对象与参数 clazz 不一致。
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
// 加锁
synchronized (this.injectionMetadataCache) {
// 重新获取
metadata = this.injectionMetadataCache.get(cacheKey);
// 二次校验
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
// 清除传入的属性
if (metadata != null) {
metadata.clear(pvs);
}
// 构建依赖数据(需要注入的元数据)
metadata = buildAutowiringMetadata(clazz);
// 添加到缓存
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
// 返回结果
return metadata;
}

/**
* 构建依赖数据
*/
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
// 声明注入元素
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;

do {
// 本次循环解析到的依赖元素
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();

// 遍历每个字段
ReflectionUtils.doWithLocalFields(targetClass, field -> {
// 获取给定注解(@Annotation、@Value、@Inject)的属性值
AnnotationAttributes ann = findAutowiredAnnotation(field);
// 如果不为空则表示存在需要注入的属性
if (ann != null) {
// static 标识的字段无法注入
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static fields: " + field);
}
return;
}
// 确定注入字段是否为必须(不能为空)
boolean required = determineRequiredStatus(ann);
// 创建一个注入元素并添加到 currElements 集合中
currElements.add(new AutowiredFieldElement(field, required));
}
});

// 遍历每个方法
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
// 获取方法对应的原始方法,方法有可能是桥接方法,则需要找到对应的原始方法,否则返回参数本身。
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
// 校验 method 与 bridgedMethod 的参数列表以及返回类型是否一致
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
// 同样获取指定注解的属性
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
// 找到相应的目标方法,例如这个方法在接口中定义,但是 clazz 是该接口的实现类,则返回实现类中的方法
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
// 同样不支持 static 方法
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static methods: " + method);
}
return;
}
// 如果方法没有参数,则打印 log
if (method.getParameterCount() == 0) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
// 确定注入字段是否为必须(不能为空)
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
// 添加到 currElements 集合
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});

// 添加到整个结果集的列表中
elements.addAll(0, currElements);
// 更新目标类为父类
targetClass = targetClass.getSuperclass();
}
// 有父类 且 父类不是 Object 则继续循环
while (targetClass != null && targetClass != Object.class);

// 返回该 bean 需要注入的元数据
return new InjectionMetadata(clazz, elements);
}

@Nullable
private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
// 判断是否被注解标识
if (ao.getAnnotations().length > 0) {
// 遍历注解列表
for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
// 获取注解属性值
AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
// 不为空则返回
if (attributes != null) {
return attributes;
}
}
}
return null;
}

}

装配 bean 依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**
* 用于解析 bean 依赖,装配 bean 属性的 Bean 后继处理器
*
*/
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {

/**
* 后处理 bean 属性,查询 bean 依赖的元数据,并装配 bean
*/
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// 查询 bean 依赖元数据
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
// 注入 bean
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
// 返回属性
return pvs;
}

/**
* 表示关于被注解标识的字段的注入信息的类
*/
private class AutowiredFieldElement extends InjectionMetadata.InjectedElement {

private final boolean required;

private volatile boolean cached = false;

@Nullable
private volatile Object cachedFieldValue;

public AutowiredFieldElement(Field field, boolean required) {
super(field, null);
this.required = required;
}

/**
* 注入方法
*/
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
// 当前需要注入的对象
Field field = (Field) this.member;
Object value;
// 如果已缓存
if (this.cached) {
// 缓存中读取
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
// 创建依赖描述符
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
// 设置声明类
desc.setContainingClass(bean.getClass());
// 被注入的 bean 名称
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
// 解析该对象并(实例化依赖对象)
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
// 加锁
synchronized (this) {
// 如果没有被缓存
if (!this.cached) {
// 如果实例化的对象不为空
if (value != null || this.required) {
// 将依赖描述符进行缓存
this.cachedFieldValue = desc;
// 注入 bean 依赖
registerDependentBeans(beanName, autowiredBeanNames);
// 如果只有一个依赖
if (autowiredBeanNames.size() == 1) {
// 缓存值替换为 ShortcutDependencyDescriptor 类型
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
// 表示为已缓存
this.cached = true;
}
}
}
// 实例化对象不为空
if (value != null) {
// 设置为可访问权限
ReflectionUtils.makeAccessible(field);
// 为 bean 装配属性
field.set(bean, value);
}
}
}


/**
* 表示被注解方法的注入信息的类
*/
private class AutowiredMethodElement extends InjectionMetadata.InjectedElement {

private final boolean required;

private volatile boolean cached = false;

@Nullable
private volatile Object[] cachedMethodArguments;

// 构造函数
public AutowiredMethodElement(Method method, boolean required, @Nullable PropertyDescriptor pd) {
super(method, pd);
this.required = required;
}

// 注入方法
@Override
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
// 是否需要跳过
if (checkPropertySkipping(pvs)) {
return;
}
Method method = (Method) this.member;
Object[] arguments;
// 是否已缓存
if (this.cached) {
// 使用已缓存的参数值
arguments = resolveCachedArguments(beanName);
}
else {
// 参数类型列表
Class<?>[] paramTypes = method.getParameterTypes();
// 参数值列表
arguments = new Object[paramTypes.length];
// 依赖描述符
DependencyDescriptor[] descriptors = new DependencyDescriptor[paramTypes.length];
Set<String> autowiredBeans = new LinkedHashSet<>(paramTypes.length);
Assert.state(beanFactory != null, "No BeanFactory available");
TypeConverter typeConverter = beanFactory.getTypeConverter();
for (int i = 0; i < arguments.length; i++) {
// 方法参数
MethodParameter methodParam = new MethodParameter(method, i);
// 依赖描述符
DependencyDescriptor currDesc = new DependencyDescriptor(methodParam, this.required);
// 设置包含该方法的类
currDesc.setContainingClass(bean.getClass());
descriptors[i] = currDesc;
try {
// 解析依赖
Object arg = beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);
// 参数为空且 require 为 false,则跳出循环
if (arg == null && !this.required) {
arguments = null;
break;
}
// 将参数值添加到参数值列表中
arguments[i] = arg;
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);
}
}
// 加锁
synchronized (this) {
// 没有被缓存
if (!this.cached) {
// 参数不为空,则设置缓存
if (arguments != null) {
Object[] cachedMethodArguments = new Object[paramTypes.length];
System.arraycopy(descriptors, 0, cachedMethodArguments, 0, arguments.length);
registerDependentBeans(beanName, autowiredBeans);
if (autowiredBeans.size() == paramTypes.length) {
Iterator<String> it = autowiredBeans.iterator();
for (int i = 0; i < paramTypes.length; i++) {
String autowiredBeanName = it.next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {
cachedMethodArguments[i] = new ShortcutDependencyDescriptor(
descriptors[i], autowiredBeanName, paramTypes[i]);
}
}
}
this.cachedMethodArguments = cachedMethodArguments;
}
else {
this.cachedMethodArguments = null;
}
this.cached = true;
}
}
}
// 参数不为空
if (arguments != null) {
try {
// 设置可访问权限
ReflectionUtils.makeAccessible(method);
// 给定参数调用目标类的方法
method.invoke(bean, arguments);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
// 解析被缓存的参数
@Nullable
private Object[] resolveCachedArguments(@Nullable String beanName) {
Object[] cachedMethodArguments = this.cachedMethodArguments;
if (cachedMethodArguments == null) {
return null;
}
Object[] arguments = new Object[cachedMethodArguments.length];
for (int i = 0; i < arguments.length; i++) {
arguments[i] = resolvedCachedArgument(beanName, cachedMethodArguments[i]);
}
return arguments;
}
}


/**
* 具有预解析目标 bean 名称的 DependencyDescriptor 变体。
*/
private static class ShortcutDependencyDescriptor extends DependencyDescriptor {

private final String shortcut;

private final Class<?> requiredType;

public ShortcutDependencyDescriptor(DependencyDescriptor original, String shortcut, Class<?> requiredType) {
super(original);
this.shortcut = shortcut;
this.requiredType = requiredType;
}

@Override
public Object resolveShortcut(BeanFactory beanFactory) {
return beanFactory.getBean(this.shortcut, this.requiredType);
}
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/**
* 映射注入元数据的内部类,不适合直接用于应用程序
*
* <p>Used by {@link AutowiredAnnotationBeanPostProcessor},
* {@link org.springframework.context.annotation.CommonAnnotationBeanPostProcessor} and
* {@link org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor}.
*/
public class InjectionMetadata {

private static final Log logger = LogFactory.getLog(InjectionMetadata.class);

private final Class<?> targetClass;

private final Collection<InjectedElement> injectedElements;

@Nullable
private volatile Set<InjectedElement> checkedElements;

/**
* 构造函数,初始化目标类和需要注入的元素
*/
public InjectionMetadata(Class<?> targetClass, Collection<InjectedElement> elements) {
this.targetClass = targetClass;
this.injectedElements = elements;
}


public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set<InjectedElement> checkedElements = new LinkedHashSet<>(this.injectedElements.size());
for (InjectedElement element : this.injectedElements) {
Member member = element.getMember();
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
beanDefinition.registerExternallyManagedConfigMember(member);
checkedElements.add(element);
if (logger.isTraceEnabled()) {
logger.trace("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedElements = checkedElements;
}

/**
* 注入方法
*/
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
// 如果需要注入的元素不为空
if (!elementsToIterate.isEmpty()) {
// 遍历元素
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
// 调用元素的注入方法
element.inject(target, beanName, pvs);
}
}
}

/**
* 清除属性跳过以包含的元素
* @since 3.2.13
*/
public void clear(@Nullable PropertyValues pvs) {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
element.clearPropertySkipping(pvs);
}
}
}

/**
* 校验是否需要重新解析 bean 依赖
*/
public static boolean needsRefresh(@Nullable InjectionMetadata metadata, Class<?> clazz) {
return (metadata == null || metadata.targetClass != clazz);
}


/**
* 一个单独的被注入的元素
*/
public abstract static class InjectedElement {

protected final Member member;

protected final boolean isField;

@Nullable
protected final PropertyDescriptor pd;

@Nullable
protected volatile Boolean skip;

/**
* 构造函数,初始化需要被注入的对象以及属性值
*/
protected InjectedElement(Member member, @Nullable PropertyDescriptor pd) {
this.member = member;
this.isField = (member instanceof Field);
this.pd = pd;
}

public final Member getMember() {
return this.member;
}

protected final Class<?> getResourceType() {
if (this.isField) {
return ((Field) this.member).getType();
}
else if (this.pd != null) {
return this.pd.getPropertyType();
}
else {
return ((Method) this.member).getParameterTypes()[0];
}
}

protected final void checkResourceType(Class<?> resourceType) {
if (this.isField) {
Class<?> fieldType = ((Field) this.member).getType();
if (!(resourceType.isAssignableFrom(fieldType) || fieldType.isAssignableFrom(resourceType))) {
throw new IllegalStateException("Specified field type [" + fieldType +
"] is incompatible with resource type [" + resourceType.getName() + "]");
}
}
else {
Class<?> paramType =
(this.pd != null ? this.pd.getPropertyType() : ((Method) this.member).getParameterTypes()[0]);
if (!(resourceType.isAssignableFrom(paramType) || paramType.isAssignableFrom(resourceType))) {
throw new IllegalStateException("Specified parameter type [" + paramType +
"] is incompatible with resource type [" + resourceType.getName() + "]");
}
}
}

/**
* 这个方法或者 getResourceToInject 需要被重写
*/
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
throws Throwable {
// 如果是字段
if (this.isField) {
// 类型转换
Field field = (Field) this.member;
// 设置为可访问
ReflectionUtils.makeAccessible(field);
// 为目标类设置该字段的值
field.set(target, getResourceToInject(target, requestingBeanName));
}
else {
// 校验是否需要跳过
if (checkPropertySkipping(pvs)) {
return;
}
try {
// 类型转换
Method method = (Method) this.member;
// 设置为可访问
ReflectionUtils.makeAccessible(method);
// 调用目标类的方法
method.invoke(target, getResourceToInject(target, requestingBeanName));
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}

/**
* 校验是否为需要因为期望的属性值已经被设置而跳过,也将这个受影响的属性标记为已处理
* 让其他处理器忽略掉它。
*/
protected boolean checkPropertySkipping(@Nullable PropertyValues pvs) {
// 是否表过表示为
Boolean skip = this.skip;
// skip 已设置则直接返回
if (skip != null) {
return skip;
}
// 属性值为空则不跳过
if (pvs == null) {
this.skip = false;
return false;
}
// 加锁
synchronized (pvs) {
// 更新 skip 值
skip = this.skip;
// 二次校验
if (skip != null) {
return skip;
}
// 属性描述器不为空
if (this.pd != null) {
// 作为 bean 的一部分提供了期望值
if (pvs.contains(this.pd.getName())) {
this.skip = true;
return true;
}
// 是否为 MutablePropertyValues 类型
else if (pvs instanceof MutablePropertyValues) {
// 把当前属性描述其添加到给定属性中去
((MutablePropertyValues) pvs).registerProcessedProperty(this.pd.getName());
}
}
// 其他情况 不跳过
this.skip = false;
return false;
}
}

/**
* 清除该元素的跳过属性
* @since 3.2.13
*/
protected void clearPropertySkipping(@Nullable PropertyValues pvs) {
if (pvs == null) {
return;
}
synchronized (pvs) {
if (Boolean.FALSE.equals(this.skip) && this.pd != null && pvs instanceof MutablePropertyValues) {
((MutablePropertyValues) pvs).clearProcessedProperty(this.pd.getName());
}
}
}

/**
* 该方法或者 inject 需要被重写
*/
@Nullable
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
return null;
}

}

}
1
2