Spring-源码相关

ApplicationContext的公共接口

1
2
3
4
# ApplicationContext的公共接口,定义寄存器和扫描方法
AnnotationConfigRegistry
void register(Class<?>... annotatedClasses);
void scan(String... basePackages);

AnnotationConfigApplicationContext

1
2
3
4
5
6
7
# 上下文 AnnotationConfigApplicationContext implements AnnotationConfigRegistry

#实例化
- 配置读取器 AnnotatedBeanDefinitionReader (此 Reader 作用为提供动态注册 Bean)
- 配置扫描器 ClassPathBeanDefinitionScanner (核心扫描加注册)
- 扫描包
- 刷新上下文

# BeanDifination 读取器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# BeanDifination 读取器
AnnotatedBeanDefinitionReader
注册 ConditionEvaluator(默认为 ConditionContextImpl)

# 注册 AnnotationConfigProcessors
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
- 注册排序器 AnnotationAwareOrderComparator
- 注册自动注入候选人解析器(AutowireCandidateResolver) ContextAnnotationAutowireCandidateResolver
- @see org.springframework.beans.factory.support.AutowireCandidateResolver
- 注册 beanFactory 后置处理器
- ConfigurationClassPostProcessor
- EventListenerMethodProcessor
- 注册后置处理器
- AutowiredAnnotationBeanPostProcessor
- CommonAnnotationBeanPostProcessor
- 注册 EventListenerFactory
- DefaultEventListenerFactory

Scan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 从基本包中提供候选组件的组件提供程. 扫描类路径, 通过应用排除和包含过滤器来识别候选组件. 此实现基于 Spring 的 MetadataReader 工具, 并由ASM ClassReader支持
ClassPathScanningCandidateComponentProvider
# 扫描类路径以查找候选组件
- Set<BeanDefinition> findCandidateComponents()
- Set<BeanDefinition> scanCandidateComponents()
- 根据包路径获取所有 class(Resource)
- 根据 Resource 获取对应的 MetadataReader(SimpleMetadataReader)
- 通过注册的 TypeFilter 过滤, 并且通过 ConditionEvaluator(默认为 ConditionContextImpl) 判断是否需要, 留下需要注册的 MetadataReader

# 判断是否有注解 @Component
- org.springframework.core.type.filter.AnnotationTypeFilter#matchSelf
# 解析@Conditional (注意 @ConditionalOnXXX 不在此时处理, 而是依赖 ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry 来取进行过滤的, 不在此处过滤)
- org.springframework.context.annotation.ConditionEvaluator#shouldSkip
# @Configuration @Component @ComponentScan @Import @ImportResource @Bean
- org.springframework.context.annotation.ConfigurationClassUtils#isConfigurationCandidate
- 如果是 ConfigurationCondition 则, 则走对应的 match 匹配. 如果不是, 则不走 match,
- 将 MetadataReader 作为入参构造 BeanDefinition(已经包含的所有该类的所有信息, 注解, 字段, 实现接口, 父类等等)

Scan

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 扫描器 ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider
注册默认过滤器(@Component, @javax.annotation.ManagedBean, @javax.inject.Named)

# 扫描
- doScan
通过父类的 findCandidateComponents 来获取所有需要加载的 BeanDefinition
- org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#findCandidateComponents

设置部分字段默认值(LazyInit, AutowireMode, DependencyCheck, InitMethodName, DestroyMethodName)
- org.springframework.context.annotation.ClassPathBeanDefinitionScanner#postProcessBeanDefinition

解析默认的注解并设置到对应 BeanDefinition 的属性(@Lazy, @Primary, @DependsOn, @Role, @Description)
- org.springframework.context.annotation.AnnotationConfigUtils#processCommonDefinitionAnnotations

构造 BeanDefinitionHolder (如果解析需要代理, 则需要特殊处理)
- org.springframework.context.annotation.AnnotationConfigUtils#applyScopedProxyMode

BeanDefinition 注册到 BeanDefinitionRegistry(AnnotationConfigApplicationContext, 实际上是注册到 BeanFactory)
- org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition
- org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition
- org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition

beanFactory 后置处理器

1
2
3
# beanFactory 后置处理器(初始化前后)
BeanFactoryPostProcessor
- void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)()

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
# bean 后置处理器(初始化前后)
BeanPostProcessor
- Object postProcessBeforeInitialization(Object bean, String beanName) (初始化前执行的回调)
- 一般对字段处理的处理器实现此方法或@PostConstruct 例: @ApolloValue @Value @ConfigurationProperties Validator.class @PostConstruct
- Object postProcessAfterInitialization(Object bean, String beanName) (初始化后执行的回调)
- 一般对于对象再包装或基于此对象初始化后执行后续行为实现此方法 例: @Scheduled AOP DataSourceInitializerPostProcessor

InitDestroyAnnotationBeanPostProcessor
- Object postProcessBeforeInitialization(Object bean, String beanName) (初始化前执行 @PostConstruct)

# 对 javax.annotation 的字段填充处理(@Resource)
CommonAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor
- PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) (处理 @Resource 字段)
- @see CommonAnnotationBeanPostProcessor#buildResourceMetadata
- @see InjectionMetadata#inject

ScheduledAnnotationBeanPostProcessor
- Object postProcessAfterInitialization(Object bean, String beanName) (初始化后执行 @Scheduled 任务)

# 增加实例化前后, 增加字段处理前回调
InstantiationAwareBeanPostProcessor extends BeanPostProcessor
- Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) (实例化前的回调)
- 目前只有需要提前实现 aop 的实现
- @see AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation

-@see AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation
- boolean postProcessAfterInstantiation(Object bean, String beanName) (实例化后属性填充前的回调)
- 如果返回 false 则说明不需要 spring 处理字段后续等操作
- @see AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

-@see AbstractAutowireCapableBeanFactory#initializeBean
- PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) (工厂处理字段前字段处理的回调)
- 只有 @Autowired @Value 的字段是通过此种方式注入
- @see AbstractAutowireCapableBeanFactory#populateBean
- PropertyValues postProcessPropertyValues()

# 对 javax.annotation 的字段填充处理(@Resource)
CommonAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor
- PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) (处理 @Resource 字段)
- @see CommonAnnotationBeanPostProcessor#buildResourceMetadata
- @see InjectionMetadata#inject


# 增加预测行为(基本参与的是预测实例化构造器)
SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor
- Class<?> predictBeanType(Class<?> beanClass, String beanName) (预测 bean 的类型)
- Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) (找出最合适的构造方法)
- @see AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors
-@see - @see AbstractAutowireCapableBeanFactory#createBeanInstance
- Object getEarlyBeanReference(Object bean, String beanName)(返回该 bean 的早期引用, 如果不是 aop 则返回参数的 bean. 如果 aop 才会处理)

# 自动注入处理器(处理 @Autotired @Value)
AutowiredAnnotationBeanPostProcessor
- PropertyValues postProcessProperties (处理 @Autowired @Value 字段. 利用反射)
- @see AutowiredFieldElement#inject
- @see AutowiredMethodElement#inject

# 合并 BeanDefinition 处理器
MergedBeanDefinitionPostProcessor extends BeanPostProcessor
- void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) (合并 BeanDefination)
- @see AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors

# 自动注入处理器(处理 @Autotired @Value)
AutowiredAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessor
# 初始化和销毁处理器
InitDestroyAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessor
# 任务处理器
ScheduledAnnotationBeanPostProcessor implements MergedBeanDefinitionPostProcessor

# 销毁前回调
DestructionAwareBeanPostProcessor extends BeanPostProcessor
- void postProcessBeforeDestruction (销毁前回调)
- @see DisposableBeanAdapter#destroy

# 初始化和销毁处理器
InitDestroyAnnotationBeanPostProcessor implements DestructionAwareBeanPostProcessor
- void postProcessBeforeDestruction (销毁前执行 destroy 方法)

# ScheduledAnnotationBeanPostProcessor
- void postProcessBeforeDestruction (销毁前执行 任务 cancel 方法)

BeanPostProcessor 总结

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
总结 BeanPostProcessor 顺序   
1. 实例化前执行方法 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
- 特殊 aop 返回的对象 @see AbstractAutoProxyCreator#postProcessBeforeInstantiation
1. 实例化获取构造器方法 SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
1. 实例化后执行方法 InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
- 暂无发现有实现此方法
1. 实例化后填充属性 InstantiationAwareBeanPostProcessor#postProcessProperties
1. 初始化前执行 Aware 回调(BeanNameAware, BeanClassLoaderAware, BeanFactoryAware) AbstractAutowireCapableBeanFactory#invokeAwareMethods
1. 初始化前执行方法 BeanPostProcessor#postProcessBeforeInitialization
- apollo 设置属性方法
- Aware 执行对应回调
- ConfigurationProperties 绑定属性
- ImportAware 执行回调
- @PostConstruct 执行
1. 初始化方法(InitializingBean#afterPropertiesSet, init-method) AbstractAutowireCapableBeanFactory#invokeInitMethods
1. 初始化后执行方法 BeanPostProcessor#postProcessAfterInitialization
- aop 包装对象
- jdbc DataSource 初始化 DataSourceInitializerInvoker 执行器
- @Scheduled 执行

创建 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
创建 bean
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
- 标记该 bean 对象正在创建
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton
- 创建检查
- 回调创建对象
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation(实例化前执行方法)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

实例化
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean
- org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate
- org.springframework.beans.BeanUtils#instantiateClass(java.lang.reflect.Constructor<T>, java.lang.Object...)

合并 BeanDifination
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors
- org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition

将对象放入一级缓存(通过工厂方式获取对象, 实际上只有 aop 有效, 非 aop 就是返回原对象), 二级缓存移除该 beanName
- org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory

填充属性(依赖注入在此处解决)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
- org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation(实例化后执行方法)
- org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties
- org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessProperties(@Autowired, @Value)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues
- org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveValueIfNecessary
-org.springframework.beans.factory.support.BeanDefinitionValueResolver#resolveReference

初始化(执行后置处理器, 执行回调函数)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods(执行 Aware 回调)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization (执行 BeanPostProcessor 前置回调)
- # @PostConstruct 在此部分处理(@see org.springframework.context.annotation.CommonAnnotationBeanPostProcessor)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods (执行 InitializingBean#afterPropertiesSet, 执行 init-method)
- org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization(执行 BeanPostProcessor 后置回调)

重新获取对象(实际作用: 通过一级缓存获取 bean 对象, 放入二级缓存, 一级缓存中删除对 bean 对象)
- org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)

- 清除创建标记
-bean 对象放入三级缓存, 一级缓存和二级缓存删除此 bean 对象

创建 Bean 流程总结

1
2
3
4
总结:
1. 先执行 @PostConstruct, 因为他是在 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation(实例化后置)
2. 后执行 InitializingBean#afterPropertiesSet
3. 最后执行 init-method

@Component

1
2
@Component
@see org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#registerDefaultFilters

@Import

1
2
3
4
5
6
7
8
9
10
11
12
@Import

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
org.springframework.context.annotation.ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry
org.springframework.context.annotation.ConfigurationClassParser#collectImports

BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry


@ComponentScan(字母顺序加载, 包含@Component @Service 等) > @Import() > @Bean(定义顺序)

@Order 声明的是初始化顺序, 不是加载顺序

@Conditional

1
2
3
4
5
6
7
8
9
10
11
12
13
@Conditional

value: org.springframework.context.annotation.Condition

org.springframework.context.annotation.Condition
boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

org.springframework.context.annotation.ConditionContext
- BeanDefinitionRegistry getRegistry();
- ConfigurableListableBeanFactory getBeanFactory();
- Environment getEnvironment();
- ResourceLoader getResourceLoader();
- ClassLoader getClassLoader();

Spring-源码相关
https://gallrax.github.io/2023/04/10/Spring源码流程/
作者
Gallrax
发布于
2023年4月10日
许可协议