Skip to content

Commit ba75a69

Browse files
committed
再看Spring源码——关于ApplicationContext,更新部分中文注释以及思维导图
1 parent 73fe407 commit ba75a69

17 files changed

+62
-44
lines changed
26.7 KB
Binary file not shown.

mindPics/SpringIOC—ApplicationContext.svg

Lines changed: 12 additions & 0 deletions
Loading
-72 Bytes
Binary file not shown.

mindPics/SpringIOC—XmlBeanFactory.svg

Lines changed: 4 additions & 4 deletions
Loading

mindPics/解析自定义标签.emmx

-162 Bytes
Binary file not shown.

spring-beans/src/main/java/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,14 +44,14 @@ public interface ConfigurableListableBeanFactory
4444
extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
4545

4646
/**
47-
* Ignore the given dependency type for autowiring:
47+
* 自动装配时忽略指定的类型:
4848
* for example, String. Default is none.
4949
* @param type the dependency type to ignore
5050
*/
5151
void ignoreDependencyType(Class<?> type);
5252

5353
/**
54-
* Ignore the given dependency interface for autowiring.
54+
* 自动装配时忽略指定的接口(http://yangbolin.cn/2016/11/12/spring-work-01/ https://www.jianshu.com/p/3c7e0608ff1f)
5555
* <p>This will typically be used by application contexts to register
5656
* dependencies that are resolved in other ways, like BeanFactory through
5757
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.

spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1622,6 +1622,7 @@ protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanW
16221622
}
16231623

16241624
/**
1625+
* 确定是否从依赖性检查中排除给定的bean属性。
16251626
* Determine whether the given bean property is excluded from dependency checks.
16261627
* <p>This implementation excludes properties defined by CGLIB and
16271628
* properties whose type matches an ignored dependency type or which

spring-beans/src/main/java/org/springframework/beans/factory/support/AutowireUtils.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,19 +111,21 @@ public static boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
111111
}
112112

113113
/**
114-
* Return whether the setter method of the given bean property is defined
115-
* in any of the given interfaces.
114+
* 返回是否在给定的接口之一中定义给定了bean属性的setter方法
115+
* Return whether the setter method of the given bean property is defined in any of the given interfaces.
116116
* @param pd the PropertyDescriptor of the bean property
117117
* @param interfaces the Set of interfaces (Class objects)
118118
* @return whether the setter method is defined by an interface
119119
*/
120120
public static boolean isSetterDefinedInInterface(PropertyDescriptor pd, Set<Class<?>> interfaces) {
121+
// 获取bean中某个属性对象在bean类中的setter方法
121122
Method setter = pd.getWriteMethod();
122123
if (setter != null) {
124+
// 获取bean的类型
123125
Class<?> targetClass = setter.getDeclaringClass();
124126
for (Class<?> ifc : interfaces) {
125-
if (ifc.isAssignableFrom(targetClass) &&
126-
ClassUtils.hasMethod(ifc, setter.getName(), setter.getParameterTypes())) {
127+
if (ifc.isAssignableFrom(targetClass) && // bean类型是否是接口的实现类
128+
ClassUtils.hasMethod(ifc, setter.getName(), setter.getParameterTypes())) { // 接口是否有入参和bean类型完全相同的setter方法
127129
return true;
128130
}
129131
}

spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,7 @@ public void preInstantiateSingletons() throws BeansException {
781781
// Trigger post-initialization callback for all applicable beans...
782782
for (String beanName : beanNames) {
783783
Object singletonInstance = getSingleton(beanName);
784+
// 如果实例化的bean是SmartInitializingSingleton类型的,在getBean结束后还需要执行bean的afterSingletonsInstantiated方法
784785
if (singletonInstance instanceof SmartInitializingSingleton) {
785786
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
786787
if (System.getSecurityManager() != null) {

spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,13 +128,14 @@ public void multicastEvent(ApplicationEvent event) {
128128
}
129129

130130
/**
131-
* 当Spring产生事件时,会默认使用该方法来广播事件,调用监听器的onApplicationEvent方法
131+
* 当Spring产生事件时,会默认使用该方法向所有的监听器进行广播事件(调用监听器的onApplicationEvent方法
132132
* @param event the event to multicast
133133
* @param eventType the type of event (can be null)
134134
*/
135135
@Override
136136
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
137137
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
138+
// 遍历通知所有的监听器
138139
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
139140
Executor executor = getTaskExecutor();
140141
if (executor != null) {

spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -522,7 +522,7 @@ public void refresh() throws BeansException, IllegalStateException {
522522
prepareRefresh();
523523

524524
// Tell the subclass to refresh the internal bean factory.
525-
// 初始化BeanFactory,并进行XML文件读取
525+
// 初始化BeanFactory,并进行XML文件读取配置,此时已经转化为beanDefinition
526526
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
527527

528528
// Prepare the bean factory for use in this context.
@@ -543,7 +543,7 @@ public void refresh() throws BeansException, IllegalStateException {
543543
registerBeanPostProcessors(beanFactory);
544544

545545
// Initialize message source for this context.
546-
// 为上下文初始化Message消息资源,即不同语言的消息体,国际化处理
546+
// 为Context初始化Message消息资源,即不同语言的消息体,国际化处理
547547
initMessageSource();
548548

549549
// Initialize event multicaster for this context.
@@ -597,7 +597,7 @@ public void refresh() throws BeansException, IllegalStateException {
597597
* active flag as well as performing any initialization of property sources.
598598
*/
599599
protected void prepareRefresh() {
600-
this.startupDate = System.currentTimeMillis();
600+
this.startupDate = System.currentTimeMillis(); // 容器刷新计时
601601
this.closed.set(false); // AtomicBoolean类型,并发
602602
this.active.set(true); // AtomicBoolean类型,并发
603603

@@ -661,7 +661,7 @@ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
661661
// 添加BeanPostProcessor,对这些Aware接口信息进行信息注入
662662
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
663663

664-
// 设置几个忽略自动装配的接口
664+
// 上一步实现Aware接口的bean由于其特殊性,所以在自动装配时需要忽略来手动注入 https://www.jianshu.com/p/3c7e0608ff1f
665665
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
666666
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
667667
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
@@ -678,7 +678,7 @@ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
678678
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
679679

680680
// Register early post-processor for detecting inner beans as ApplicationListeners.
681-
// 添加BeanPostProcessor实现:ApplicationListenerDetector,它是用来将实现了ApplicationListener接口的Bean添加到容器的监听器列表
681+
// 添加BeanPostProcessor实现:ApplicationListenerDetector,它是用来将 实现了ApplicationListener接口的Bean 添加到容器的监听器列表
682682
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
683683

684684
// Detect a LoadTimeWeaver and prepare for weaving, if found.
@@ -720,7 +720,7 @@ protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactor
720720
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
721721
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
722722

723-
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
723+
// 如果beanFactory中定义了loadTimeWeaver的bean,则检测LoadTimeWeaver并准备织入
724724
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
725725
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
726726
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
@@ -747,7 +747,7 @@ protected void initMessageSource() {
747747
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
748748
// 如果配置文件中定义了messageSource这个bean,那么将其提取并记录在ApplicationContext(this.messageSource)中
749749
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
750-
// 获取名为messageSource这个bean
750+
// 实例化名为messageSource这个bean
751751
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
752752
// Make MessageSource aware of parent MessageSource.
753753
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
@@ -1293,8 +1293,8 @@ public boolean containsLocalBean(String name) {
12931293
}
12941294

12951295
/**
1296-
* Return the internal bean factory of the parent context if it implements
1297-
* ConfigurableApplicationContext; else, return the parent context itself.
1296+
* 如果父Context实现了ConfigurableApplicationContext,则返回父Context的内部beanFactory;
1297+
* 否则,直接返回父Context本身
12981298
* @see org.springframework.context.ConfigurableApplicationContext#getBeanFactory
12991299
*/
13001300
@Nullable

spring-context/src/main/java/org/springframework/context/support/ApplicationListenerDetector.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) {
6868

6969
@Override
7070
public Object postProcessAfterInitialization(Object bean, String beanName) {
71+
// 在返回bean之前检测是否是ApplicationListener类型,如果是会添加到容器的监听器列表
7172
if (bean instanceof ApplicationListener) {
7273
// potentially not detected as a listener by getBeanNamesForType retrieval
7374
Boolean flag = this.singletonNames.get(beanName);

spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ private void startBeans(boolean autoStartupOnly) {
154154
List<Integer> keys = new ArrayList<>(phases.keySet());
155155
Collections.sort(keys);
156156
for (Integer key : keys) {
157-
phases.get(key).start();
157+
phases.get(key).start(); // 遍历调用start()方法
158158
}
159159
}
160160
}

spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ private PostProcessorRegistrationDelegate() {
5555
/**
5656
* 调用BeanFactoryPostProcessors后处理方法
5757
* @param beanFactory
58-
* @param beanFactoryPostProcessors
58+
* @param beanFactoryPostProcessors 所有硬编码的beanFactoryPostProcessors
5959
*/
6060
public static void invokeBeanFactoryPostProcessors(
6161
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
@@ -76,7 +76,7 @@ public static void invokeBeanFactoryPostProcessors(
7676

7777
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
7878

79-
// 记录已经处理的bean的hashset
79+
// 记录已经处理的bean的HashSet
8080
Set<String> processedBeans = new HashSet<>();
8181

8282
// 对BeanDefinitionRegistry类型的beanFactory处理
@@ -121,7 +121,7 @@ public static void invokeBeanFactoryPostProcessors(
121121
String[] postProcessorNames =
122122
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
123123
for (String ppName : postProcessorNames) {
124-
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
124+
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 先处理那些有顺序的BeanDefinitionRegistryPostProcessors
125125
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
126126
processedBeans.add(ppName);
127127
}
@@ -151,7 +151,7 @@ public static void invokeBeanFactoryPostProcessors(
151151
reiterate = false;
152152
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
153153
for (String ppName : postProcessorNames) {
154-
// 处理剩下的
154+
// 处理配置文件中剩下的没有顺序的BeanDefinitionRegistryPostProcessors
155155
if (!processedBeans.contains(ppName)) {
156156
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
157157
processedBeans.add(ppName);
@@ -170,9 +170,9 @@ public static void invokeBeanFactoryPostProcessors(
170170

171171
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
172172
// 激活postProcessBeanFactory方法,之前激活的是postProcessBeanDefinitionRegistry
173-
// 激活硬编码设置的BeanDefinitionRegistryPostProcessor的postProcessBeanFactory
173+
// 激活硬编码和配置文件中所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法
174174
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
175-
// 激活常规的BeanFactoryPostProcessor的postProcessBeanFactory
175+
// 激活硬编码常规的BeanFactoryPostProcessor的postProcessBeanFactory
176176
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
177177

178178
// ==============1.1.3结束之处==============
@@ -186,7 +186,7 @@ public static void invokeBeanFactoryPostProcessors(
186186

187187
// Do not initialize FactoryBeans here: We need to leave all regular beans
188188
// uninitialized to let the bean factory post-processors apply to them!
189-
// 对于配置中读取的BeanFactoryPostProcessor的处理
189+
// 对于配置文件中读取的BeanFactoryPostProcessor的处理
190190
String[] postProcessorNames =
191191
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
192192

@@ -247,15 +247,15 @@ else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
247247
*/
248248
public static void registerBeanPostProcessors(
249249
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
250-
250+
// 获取配置文件中所有BeanPostProcessor.class类型的beanName
251251
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
252252

253253
// Register BeanPostProcessorChecker that logs an info message when
254254
// a bean is created during BeanPostProcessor instantiation, i.e. when
255255
// a bean is not eligible for getting processed by all BeanPostProcessors.
256256
// BeanPostProcessorChecker是一个普通的信息打印,可能会有些情况,当Spring的配置中的后处理器还没有被注册就已经开始了bean的初始化时
257257
// 便打印出BeanPostProcessorChecker中设定的信息
258-
// 1就是指下面要加的BeanPostProcessorChecker
258+
// 获得硬编码与配置文件中的所有BeanPostProcessors,1就是指下面要加的BeanPostProcessorChecker
259259
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
260260
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
261261

@@ -271,7 +271,7 @@ public static void registerBeanPostProcessors(
271271

272272
for (String ppName : postProcessorNames) {
273273
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
274-
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
274+
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); // 实例化BeanPostProcessor
275275
priorityOrderedPostProcessors.add(pp);
276276
if (pp instanceof MergedBeanDefinitionPostProcessor) {
277277
internalPostProcessors.add(pp);
@@ -286,15 +286,15 @@ else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
286286
}
287287

288288
// First, register the BeanPostProcessors that implement PriorityOrdered.
289-
// 第一步,注册所有实现PriorityOrdered的BeanPostProcessor
289+
// 第一步,注册配置文件中所有实现PriorityOrdered的BeanPostProcessor
290290
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
291291
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
292292

293293
// Next, register the BeanPostProcessors that implement Ordered.
294-
// 第二步,注册所有实现Ordered的BeanPostProcessor
294+
// 第二步,注册配置文件中所有实现Ordered的BeanPostProcessor
295295
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
296296
for (String ppName : orderedPostProcessorNames) {
297-
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
297+
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); // 实例化
298298
orderedPostProcessors.add(pp);
299299
if (pp instanceof MergedBeanDefinitionPostProcessor) {
300300
internalPostProcessors.add(pp);
@@ -304,7 +304,7 @@ else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
304304
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
305305

306306
// Now, register all regular BeanPostProcessors.
307-
// 第三步,注册所有无序的BeanPostProcessor
307+
// 第三步,注册配置文件中所有无序的BeanPostProcessor
308308
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
309309
for (String ppName : nonOrderedPostProcessorNames) {
310310
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
@@ -316,13 +316,13 @@ else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
316316
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
317317

318318
// Finally, re-register all internal BeanPostProcessors.
319-
// 第四步,注册所有MergedBeanDefinitionPostProcessor类型的BeanPostProcessor,并非重复注册,在beanFactory中会先移除已经存在的BeanPostProcessor
319+
// 第四步,注册配置文件中所有MergedBeanDefinitionPostProcessor类型的BeanPostProcessor,并非重复注册,在beanFactory中会先移除已经存在的BeanPostProcessor
320320
sortPostProcessors(internalPostProcessors, beanFactory);
321321
registerBeanPostProcessors(beanFactory, internalPostProcessors);
322322

323323
// Re-register post-processor for detecting inner beans as ApplicationListeners,
324324
// moving it to the end of the processor chain (for picking up proxies etc).
325-
// 最后添加了ApplicationListener探测器的后处理器
325+
// 最后添加了ApplicationListener探测器的后处理器,之前已经添加过一次,再次添加会移到arrayList的末尾
326326
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
327327
}
328328

spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ public void setRequiredProperties(String... requiredProperties) {
142142
}
143143

144144
/**
145-
* 对属性进行验证
145+
* 对requiredProperties属性进行验证
146146
*/
147147
@Override
148148
public void validateRequiredProperties() {

spring-mytest/src/test/java/guo/ping/ioc/bean/CustomTagTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ public class CustomTagTest {
1818

1919
@Test
2020
public void testCustomTag() {
21-
XmlBeanFactory context = new XmlBeanFactory(new ClassPathResource("customTag-Test.xml"));
22-
// ApplicationContext context = new ClassPathXmlApplicationContext("${config}");
21+
// XmlBeanFactory context = new XmlBeanFactory(new ClassPathResource("customTag-Test.xml"));
22+
ApplicationContext context = new ClassPathXmlApplicationContext("${config}");
2323
User user = (User) context.getBean("testUserBean");
2424
Order order = (Order) context.getBean("testOrderBean");
2525
System.out.println(user);

spring-mytest/src/test/java/guo/ping/ioc/bean/MyBeanFactoryPostProcessorTest.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ public class MyBeanFactoryPostProcessorTest {
2020

2121
@Test
2222
public void testMyBeanFactoryPostProcessor() {
23-
ConfigurableListableBeanFactory bf = new XmlBeanFactory(new ClassPathResource("selfBeanFactoryPostProcessor-Test.xml"));
24-
BeanFactoryPostProcessor bfpp = (BeanFactoryPostProcessor) bf.getBean("myBeanFactoryPostProcessor");
25-
// ApplicationContext bf = new ClassPathXmlApplicationContext("selfBeanFactoryPostProcessor-Test.xml");
26-
bfpp.postProcessBeanFactory(bf);
23+
// ConfigurableListableBeanFactory bf = new XmlBeanFactory(new ClassPathResource("selfBeanFactoryPostProcessor-Test.xml"));
24+
// BeanFactoryPostProcessor bfpp = (BeanFactoryPostProcessor) bf.getBean("myBeanFactoryPostProcessor");
25+
ApplicationContext bf = new ClassPathXmlApplicationContext("selfBeanFactoryPostProcessor-Test.xml");
26+
// bfpp.postProcessBeanFactory(bf);
2727
User user = (User) bf.getBean("user");
2828
System.out.println(user);
2929
}

0 commit comments

Comments
 (0)