Devin's Blogs

个人点滴记录

FrameworkServlet#service

定位: org.springframework.web.servlet.FrameworkServlet#service

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获得请求方法
HttpMethod httpMethod = HttpMethod.resolve(request.getMethod());
// 处理patch请求
if (httpMethod == HttpMethod.PATCH || httpMethod == null) {
processRequest(request, response);
}
else {
// 处理其他类型的请求
super.service(request, response);
// 此父类方法调用了 javax.servlet.http.HttpServlet#doGet/doPost 等方法
// 同时子类 FrameworkServlet 重写了 doGet/doPost, 继续调用了 FrameworkServlet#processRequest
// 即此方法最终都会调用 FrameworkServlet#processRequest
}
}

FrameworkServlet#processRequest

定位: org.springframework.web.servlet.FrameworkServlet#processRequest

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
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 记录当前时间,用于计算处理请求花费的时间
long startTime = System.currentTimeMillis();
// 记录异常,用于保存处理请求过程中发送的异常
Throwable failureCause = null;

// 获取LocaleContextHolder中原来保存的LocaleContext(保存的本地化信息)
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
// 获取当前请求的LocaleContext
LocaleContext localeContext = buildLocaleContext(request);

// 获取RequestContextHolder总原来保存的RequestAttribute(管理request和session的属性)
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
// 获取当前请求的ServletRequestAttribute
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

// 获取异步管理器
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

// 将当前请求的LocaleContext和ServletRequestAttribute设置到LocaleContextHolder和RequestContextHolder
initContextHolders(request, localeContext, requestAttributes);

try {
// 执行真正的逻辑
doService(request, response);
}
catch (ServletException | IOException ex) {
// 记录抛出的异常
failureCause = ex;
throw ex;
}
catch (Throwable ex) {
// 记录抛出的异常
failureCause = ex;
throw new NestedServletException("Request processing failed", ex);
}

finally {
// 恢复原来的LocaleContext和ServletRequestAttributes到LocaleContextHolder和RequestContextHolder中
resetContextHolders(request, previousLocaleContext, previousAttributes);
if (requestAttributes != null) {
requestAttributes.requestCompleted();
}
// 如果日志级别为debug,则打印请求日志
logResult(request, response, failureCause, asyncManager);
// 发布ServletRequestHandledEvent请求处理完成事件
publishRequestHandledEvent(request, response, startTime, failureCause);
}
}

DispatcherServlet#doService

定位: org.springframework.web.servlet.DispatcherServlet#doService

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
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 如果日志级别为 DEBUG,则打印请求日志
logRequest(request);

// Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.
// 当include请求时对request的Attribute做快照备份
Map<String, Object> attributesSnapshot = null;
if (WebUtils.isIncludeRequest(request)) {
attributesSnapshot = new HashMap<>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith(DEFAULT_STRATEGIES_PREFIX)) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}

// Make framework objects available to handlers and view objects.
// 设置Spring框架中的常用对象到request属性中,这四个属性会在handler和view中使用
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());

// FlashMap的相关配置,主要用于Redirect转发时参数的传递,此处有一个应用场景:如果post请求是提交表单,提交完之后redirect到一个显示订单的页面,
// 此时需要知道一些订单的信息,但redirect本身没有提交参数的功能,如果想传递参数,那么就必须要写到url,而url有长度的限制同时还容易对外暴露,此时
// 可以使用flashMap来传递参数,
if (this.flashMapManager != null) {
FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
if (inputFlashMap != null) {
request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
}
request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);
}
try {
// 执行请求的分发
doDispatch(request, response);
}
finally {
// 异步处理相关
if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
// Restore the original attribute snapshot, in case of an include.
// 还原request快照的属性
if (attributesSnapshot != null) {
restoreAttributesAfterInclude(request, attributesSnapshot);
}
}
}
}

DispatcherServlet#doDispatch

定位: org.springframework.web.servlet.DispatcherServlet#doDispatch

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
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 实际处理时所用的request,如果不是上传请求,则直接使用接收到的request,否则封装成上传类型的request
HttpServletRequest processedRequest = request;
// 处理请求的处理器链(包含处理器和对应的interceptor)
HandlerExecutionChain mappedHandler = null;
// 是不是上传请求的标志
boolean multipartRequestParsed = false;

// 获取异步管理器
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

try {
// 封装model和view的容器
ModelAndView mv = null;
// 处理请求过程中抛出的异常,但是不包含渲染过程中抛出的异常
Exception dispatchException = null;

try {
// 检测请求是否为上传请求,如果是则通过multipartResolver将其封装成MultipartHttpServletRequest对象
processedRequest = checkMultipart(request);
// 设置上传请求的标志
multipartRequestParsed = (processedRequest != request);

// Determine handler for the current request.
// 获得请求对应的HandlerExecutionChain对象(HandlerMethod和HandlerInterceptor拦截器们)
mappedHandler = getHandler(processedRequest);
// 如果获取不到,则根据配置抛出异常或返回404错误
if (mappedHandler == null) {
noHandlerFound(processedRequest, response);
return;
}

// Determine handler adapter for the current request.
// 获得当前handler对应的HandlerAdapter对象
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

// Process last-modified header, if supported by the handler.
// 处理GET、HEAD请求的Last-Modified,当浏览器第一次跟服务器请求资源时,服务器会在返回的请求头里包含一个last_modified的属性,
// 代表资源最后时什么时候修改的,在浏览器以后发送请求的时候,会同时发送之前接收到的Last_modified.服务器接收到带last_modified的请求后,
// 会跟实际资源的最后修改时间做对比,如果过期了返回新的资源,否则直接返回304表示未过期,直接使用之前缓存的结果即可
String method = request.getMethod();
boolean isGet = "GET".equals(method);
if (isGet || "HEAD".equals(method)) {
// 获取请求中服务器端最后被修改时间
long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
return;
}
}

// 执行响应的Interceptor的preHandler
// 注意:该方法如果有一个拦截器的前置处理返回false,则开始倒序触发所有的拦截器的 已完成处理
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}

// Actually invoke the handler.
// 真正的调用handler方法,也就是执行对应的方法,并返回视图
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

// 如果需要异步处理,直接返回
if (asyncManager.isConcurrentHandlingStarted()) {
return;
}

// 当view为空时,根据request设置默认的view
applyDefaultViewName(processedRequest, mv);
// 执行响应的interceptor的postHandler方法
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
// 记录异常
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
// 处理返回结果,包括处理异常、渲染页面、触发Interceptor的afterCompletion
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
// 已完成处理 拦截器
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
// 完成处理激活触发器
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
// 判断是否执行异步请求
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
// 删除上传请求的资源
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}

MultipartResolver

定位: org.springframework.web.servlet.DispatcherServlet#initMultipartResolver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void initMultipartResolver(ApplicationContext context) {
try {
// MULTIPART_RESOLVER_BEAN_NAME = "multipartResolver"
// 从spring上下文获取名称为 multipartResolver ,类型为MultipartResolver的Bean
this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, MultipartResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("Detected " + this.multipartResolver);
}
else if (logger.isDebugEnabled()) {
logger.debug("Detected " + this.multipartResolver.getClass().getSimpleName());
}
}
catch (NoSuchBeanDefinitionException ex) {
// Default is no multipart resolver.
this.multipartResolver = null;
if (logger.isTraceEnabled()) {
logger.trace("No MultipartResolver '" + MULTIPART_RESOLVER_BEAN_NAME + "' declared");
}
}
}

LocaleResolver

定位: org.springframework.web.servlet.DispatcherServlet#initLocaleResolver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void  initLocaleResolver(ApplicationContext context) {
try {
// LOCALE_RESOLVER_BEAN_NAME = "localeResolver"
// 从上下文中获取Bean名称为 LocaleResolver的对象
this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("Detected " + this.localeResolver);
}
else if (logger.isDebugEnabled()) {
logger.debug("Detected " + this.localeResolver.getClass().getSimpleName());
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
// 从配置文件中获取默认的AcceptHeaderLocaleResolver对象
this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("No LocaleResolver '" + LOCALE_RESOLVER_BEAN_NAME +
"': using default [" + this.localeResolver.getClass().getSimpleName() + "]");
}
}
}

ThemeResolver

定位: org.springframework.web.servlet.DispatcherServlet#initThemeResolver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private void initThemeResolver(ApplicationContext context) {
try {
// THEME_RESOLVER_BEAN_NAME = "themeResolver"
this.themeResolver = context.getBean(THEME_RESOLVER_BEAN_NAME, ThemeResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("Detected " + this.themeResolver);
}
else if (logger.isDebugEnabled()) {
logger.debug("Detected " + this.themeResolver.getClass().getSimpleName());
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
// 从配置文件中获取默认的FixedThemeResolver
this.themeResolver = getDefaultStrategy(context, ThemeResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("No ThemeResolver '" + THEME_RESOLVER_BEAN_NAME +
"': using default [" + this.themeResolver.getClass().getSimpleName() + "]");
}
}
}

HandlerMapping

定位: org.springframework.web.servlet.DispatcherServlet#initHandlerMappings

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
private void initHandlerMappings(ApplicationContext context) {
// 将handlerMappings置空
this.handlerMappings = null;

// 如果开启探测功能,则扫描已注册的HandlerMapping的bean,添加到handlerMappings中
if (this.detectAllHandlerMappings) {
// Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
// 扫描已注册的handlerMapping的bean
Map<String, HandlerMapping> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
// 添加到handlerMappings中,并进行排序
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList<>(matchingBeans.values());
// We keep HandlerMappings in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
}
// 如果关闭探测功能,则获取Bean名称为handlerMapping对应的bean,将其添加到handlerMappings
else {
try {
// HANDLER_MAPPING_BEAN_NAME = "handlerMapping"
HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerMapping later.
}
}

// Ensure we have at least one HandlerMapping, by registering
// a default HandlerMapping if no other mappings are found.
// 如果未获得到,则获得默认配置的handlerMapping类
if (this.handlerMappings == null) {
this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
if (logger.isTraceEnabled()) {
logger.trace("No HandlerMappings declared for servlet '" + getServletName() +
"': using default strategies from DispatcherServlet_test.properties");
}
}
}

HandlerAdapter

定位: org.springframework.web.servlet.DispatcherServlet#initHandlerAdapters

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
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;

if (this.detectAllHandlerAdapters) {
// Find all HandlerAdapters in the ApplicationContext, including ancestor contexts.
Map<String, HandlerAdapter> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList<>(matchingBeans.values());
// We keep HandlerAdapters in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerAdapters);
}
}
else {
try {
// HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter"
HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default HandlerAdapter later.
}
}

// Ensure we have at least some HandlerAdapters, by registering
// default HandlerAdapters if no other adapters are found.
// 如果未获得到,则获得默认配置的HandlerAdapter类,HttpRequestHandlerAdapter,SimpleControllerHandlerAdapter,RequestMappingHandlerAdapter
if (this.handlerAdapters == null) {
this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class);
if (logger.isTraceEnabled()) {
logger.trace("No HandlerAdapters declared for servlet '" + getServletName() +
"': using default strategies from DispatcherServlet_test.properties");
}
}
}

HandlerExceptionResolver

定位: org.springframework.web.servlet.DispatcherServlet#initHandlerExceptionResolvers

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
private void initHandlerExceptionResolvers(ApplicationContext context) {
// 置空 handlerExceptionResolver 处理
this.handlerExceptionResolvers = null;

// 自动扫描handlerExceptionResolver类型的bean
if (this.detectAllHandlerExceptionResolvers) {
// Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts.
Map<String, HandlerExceptionResolver> matchingBeans = BeanFactoryUtils
.beansOfTypeIncludingAncestors(context, HandlerExceptionResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerExceptionResolvers = new ArrayList<>(matchingBeans.values());
// We keep HandlerExceptionResolvers in sorted order.
AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers);
}
}
// 获取名字为HANDLER_EXCEPTION_RESOLVER_BEAN_NAME的bean
else {
try {
// HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver"
HandlerExceptionResolver her =
context.getBean(HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
this.handlerExceptionResolvers = Collections.singletonList(her);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, no HandlerExceptionResolver is fine too.
}
}

// Ensure we have at least some HandlerExceptionResolvers, by registering
// default HandlerExceptionResolvers if no other resolvers are found.
// 如果未获得到,则获取默认配置的handlerExceptionResolver类,ExceptionHandlerExceptionResolver,ResponseStatusExceptionResolver,DefaultHandlerExceptionResolver
if (this.handlerExceptionResolvers == null) {
this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("No HandlerExceptionResolvers declared in servlet '" + getServletName() +
"': using default strategies from DispatcherServlet_test.properties");
}
}
}

RequestToViewNameTranslator

定位: org.springframework.web.servlet.DispatcherServlet#initRequestToViewNameTranslator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private void initRequestToViewNameTranslator(ApplicationContext context) {
try {
// REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME = "viewNameTranslator"
this.viewNameTranslator =
context.getBean(REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME, RequestToViewNameTranslator.class);
if (logger.isTraceEnabled()) {
logger.trace("Detected " + this.viewNameTranslator.getClass().getSimpleName());
}
else if (logger.isDebugEnabled()) {
logger.debug("Detected " + this.viewNameTranslator);
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
// 如果未找到,则获取默认的 RequestToViewNameTranslator 对象,DefaultRequestToViewNameTranslator
this.viewNameTranslator = getDefaultStrategy(context, RequestToViewNameTranslator.class);
if (logger.isTraceEnabled()) {
logger.trace("No RequestToViewNameTranslator '" + REQUEST_TO_VIEW_NAME_TRANSLATOR_BEAN_NAME +
"': using default [" + this.viewNameTranslator.getClass().getSimpleName() + "]");
}
}
}

ViewResolver

定位: org.springframework.web.servlet.DispatcherServlet#initViewResolvers

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
private void initViewResolvers(ApplicationContext context) {
// 置空 viewResolvers 处理
this.viewResolvers = null;

/// 自动扫描 ViewResolver 类型的 Bean
if (this.detectAllViewResolvers) {
// Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
Map<String, ViewResolver> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
if (!matchingBeans.isEmpty()) {
this.viewResolvers = new ArrayList<>(matchingBeans.values());
// We keep ViewResolvers in sorted order.
AnnotationAwareOrderComparator.sort(this.viewResolvers);
}
}
// 获得名字为VIEW_RESOLVER_BEAN_NAME的bean
else {
try {
// VIEW_RESOLVER_BEAN_NAME = "viewResolver"
ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
this.viewResolvers = Collections.singletonList(vr);
}
catch (NoSuchBeanDefinitionException ex) {
// Ignore, we'll add a default ViewResolver later.
}
}

// Ensure we have at least one ViewResolver, by registering
// a default ViewResolver if no other resolvers are found.
// 如果未获得到,则获取默认配置的ViewResolver对象
if (this.viewResolvers == null) {
this.viewResolvers = getDefaultStrategies(context, ViewResolver.class);
if (logger.isTraceEnabled()) {
logger.trace("No ViewResolvers declared for servlet '" + getServletName() +
"': using default strategies from DispatcherServlet_test.properties");
}
}
}

FlashMapManager

定位: org.springframework.web.servlet.DispatcherServlet#initFlashMapManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private void initFlashMapManager(ApplicationContext context) {
try {
this.flashMapManager = context.getBean(FLASH_MAP_MANAGER_BEAN_NAME, FlashMapManager.class);
if (logger.isTraceEnabled()) {
logger.trace("Detected " + this.flashMapManager.getClass().getSimpleName());
}
else if (logger.isDebugEnabled()) {
logger.debug("Detected " + this.flashMapManager);
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
// 未找到,则获取默认的 FlashMapManager 对象,SessionFlashMapManager
this.flashMapManager = getDefaultStrategy(context, FlashMapManager.class);
if (logger.isTraceEnabled()) {
logger.trace("No FlashMapManager '" + FLASH_MAP_MANAGER_BEAN_NAME +
"': using default [" + this.flashMapManager.getClass().getSimpleName() + "]");
}
}
}
getDefaultStrategy 给定策略接口的默认策略对象

定位: org.springframework.web.servlet.DispatcherServlet#getDefaultStrategy

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
protected <T> T getDefaultStrategy(ApplicationContext context, Class<T> strategyInterface) {
List<T> strategies = getDefaultStrategies(context, strategyInterface);
if (strategies.size() != 1) {
throw new BeanInitializationException(
"DispatcherServlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
}
return strategies.get(0);
}
/**
* 为给定的策略接口创建一个默认策略对象列表。
* 默认实现使用“DispatcherServlet _test.properties”文件(在包作为DispatcherServlet类)来确定类名。它实例化策略对象通过上下文的BeanFactory。
*
*/
protected <T> List<T> getDefaultStrategies(ApplicationContext context, Class<T> strategyInterface) {
// 获得strategyInterface对应的value值
String key = strategyInterface.getName();
// 创建value对应的对象们,并返回
String value = defaultStrategies.getProperty(key);
if (value != null) {
// 基于","分隔,创建classNames数组
String[] classNames = StringUtils.commaDelimitedListToStringArray(value);
// 创建strategyInterface集合
List<T> strategies = new ArrayList<>(classNames.length);
// 遍历classNames数组,创建对应的类,添加到strategyInterface中
for (String className : classNames) {
try {
// 获得className类
Class<?> clazz = ClassUtils.forName(className, DispatcherServlet.class.getClassLoader());
// 创建className对应的类,并添加到strategies中
Object strategy = createDefaultStrategy(context, clazz);
strategies.add((T) strategy);
}
catch (ClassNotFoundException ex) {
throw new BeanInitializationException(
"Could not find DispatcherServlet's default strategy class [" + className +
"] for interface [" + key + "]", ex);
}
catch (LinkageError err) {
throw new BeanInitializationException(
"Unresolvable class definition for DispatcherServlet's default strategy class [" +
className + "] for interface [" + key + "]", err);
}
}
return strategies;
}
else {
return new LinkedList<>();
}
}

Spring 容器启动

ContextLoader#initWebApplicationContext

定位: org.springframework.web.context.ContextLoader#initWebApplicationContext

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
// org.springframework.web.context.ContextLoaderListener#contextInitialized
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
// web.xml中存在多次ContextLoader定义
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}

servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();

try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
// 初始化context,第一次执行的时候获取到一个root webApplicationcontext
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 将创建的context对象记录在servletContext中,创建并且准备好了spring容器
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}

if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}

return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}

ContextLoader#configureAndRefreshWebApplicationContext

定位: org.springframework.web.context.ContextLoader#configureAndRefreshWebApplicationContext

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
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}

wac.setServletContext(sc);
// 获取配置的Spring参数配置文件
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}

// 设置环境变量
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}

// 启动容器前设置上下文信息
customizeContext(sc, wac);
// 启动 Spring 容器
wac.refresh();
}

SpringMVC 容器启动

HttpServletBean#init

定位: org.springframework.web.servlet.HttpServletBean#init

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
public final void init() throws ServletException {

// Set bean properties from init parameters.
// 将servlet中配置的init-param参数封装到pvs变量中
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
// 将当前的servlet对象转化成BeanWrapper对象,从而能够以spring的方法来将pvs注入到该beanWrapper中
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
// 注册自定义属性编辑器,一旦有Resource类型的属性,将会使用ResourceEditor进行解析
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
// 模板方法,可以在子类调用,做一些初始化工作,bw代表的是DispatcherServlet
initBeanWrapper(bw);
// 以spring的方式来将pvs注入到该beanWrapper对象中,将配置的初始化值(contextConfigLocation)设置到DispatcherServlet
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}

// Let subclasses do whatever initialization they like.
// 模板方法,子类初始化的入口方法,查看FrameworkServlet#initServletBean方法
initServletBean();
}

FrameworkServlet#initServletBean

定位: org.springframework.web.servlet.FrameworkServlet#initServletBean

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
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring " + getClass().getSimpleName() + " '" + getServletName() + "'");
if (logger.isInfoEnabled()) {
logger.info("Initializing Servlet '" + getServletName() + "'");
}
// 记录开启时间
long startTime = System.currentTimeMillis();

try {
// 创建或刷新WebApplicationContext实例并对servlet功能所使用的变量进行初始化
this.webApplicationContext = initWebApplicationContext();
// 模板方法,空实现,留给子类扩展
initFrameworkServlet();
}
catch (ServletException | RuntimeException ex) {
logger.error("Context initialization failed", ex);
throw ex;
}

if (logger.isDebugEnabled()) {
String value = this.enableLoggingRequestDetails ?
"shown which may lead to unsafe logging of potentially sensitive data" :
"masked to prevent unsafe logging of potentially sensitive data";
logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
"': request parameters and headers will be " + value);
}

if (logger.isInfoEnabled()) {
logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
}
}

FrameworkServlet#initWebApplicationContext

定位: org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext

所有的前后端交互的框架都是以servlet为基础的,所以在使用springmvc的时候,默认会把自己的容器设置成 ServletContext 的属性,
默认根容器的key为 WebApplicationContext.Root,定义在WebApplicationContext中,所以在获取的时候只需要调用ServletContext.getAttribute即可

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
protected WebApplicationContext initWebApplicationContext() {
// 获得根 WebApplicationContext 对象
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
// 获得webApplicationContext wac对象
WebApplicationContext wac = null;

// 如果构造方法中已经传入webApplicationContext属性,则直接使用
// 此方式主要用于servlet3.0之后的环境,也就是说可以通过ServletContext.addServlet的方法注册servlet,此时就可以在创建FrameworkServlet和
// 其子类的时候通过构造方法传递已经准备好的webApplicationContext
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
// 如果是ConfigurationWebApplicationContext类型,并且未激活,则进行初始化
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
// 未激活
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
// 配置和刷新上下文环境
configureAndRefreshWebApplicationContext(cwac);
}
}
}
// 从servletContext获取对应的webApplicationContext对象
// 此方式需要在配置Servlet的时候将servletContext中的webApplicationContext的name配置到contextAttribute属性就可以
/*
<servlet>
<servlet-name>mvc-test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--SpringMVC配置文件-->
<init-param>
<param-name>contextAttribute</param-name>
<param-value>val</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
*/
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
// 当前面两种方式都无效的情况下会创建一个webApplicationContext对象,一般情况下都是使用这样的方式
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}

// 将contextRefreshedEvent事件没有触发时调用此方法,模板方法,可以在子类重写
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
synchronized (this.onRefreshMonitor) {
onRefresh(wac);
}
}

// 将applicationContext设置到servletContext中
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
}

return wac;
}
FrameworkServlet#createWebApplicationContext

定位: org.springframework.web.servlet.FrameworkServlet#createWebApplicationContext(org.springframework.web.context.WebApplicationContext)

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
protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
return createWebApplicationContext((ApplicationContext) parent);
}
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
// 获取servlet的初始化参数contextClass,如果没有配置默认为XmlWebApplicationContext.class
Class<?> contextClass = getContextClass();
// 如果非ConfigurableWebApplicationContext类型,抛出ConfigurableWebApplicationContext异常
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
// 通过反射方式实例化contextClass
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

// 设置environment
wac.setEnvironment(getEnvironment());
// parent为在ContextLoaderListener中创建的实例,在ContextLoaderListener加载的时候初始化的WebApplicationContext类型实例
wac.setParent(parent);
// 获取contextConfigLocation属性,配置在servlet初始化参数中
String configLocation = getContextConfigLocation();
if (configLocation != null) {
// 将设置的contextConfigLocation参数传给wac,默认传入WEB-INFO/servletName-servlet.xml
wac.setConfigLocation(configLocation);
}
// 配置和初始化wac
configureAndRefreshWebApplicationContext(wac);

return wac;
}
FrameworkServlet#configureAndRefreshWebApplicationContext

定位: org.springframework.web.servlet.FrameworkServlet#configureAndRefreshWebApplicationContext

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
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
// 如果wac使用了默认编号,则重新设置id属性
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
// 使用contextId属性
if (this.contextId != null) {
wac.setId(this.contextId);
}
// 自动生成
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}

// 设置wac的servletContext、servletConfig、namespace属性
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
// 添加监听器sourceFilteringListener到wac中,实际监听的是ContextRefreshListener所监听的事件,监听ContextRefreshedEvent事件,
// 当接收到消息之后会调用onApplicationEvent方法,调用onRefresh方法,并将refreshEventReceived标志设置为true,表示已经refresh过
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
// 获取环境对象并且添加相关的属性
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
}

// 执行处理完WebApplicationContext后的逻辑,此处为空方法,不做任何实现
postProcessWebApplicationContext(wac);
// 执行自定义初始化context
applyInitializers(wac);
// 刷新wac,从而初始化wac
wac.refresh();
}

FrameworkServlet#onRefresh

定位: org.springframework.web.servlet.DispatcherServlet#onRefresh

SpringMVC 容器启动后, 发送事件 ContextRefreshedEvent 后, 进行初始化
初始化 SpringMVC 内置的九大组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void onRefresh(ApplicationContext context) {
initStrategies(context);
}
protected void initStrategies(ApplicationContext context) {
// 初始化 MultipartResolver:主要用来处理文件上传.如果定义过当前类型的bean对象,那么直接获取,如果没有的话,可以为null
initMultipartResolver(context);
// 初始化 LocaleResolver:主要用来处理国际化配置,基于URL参数的配置(AcceptHeaderLocaleResolver),基于session的配置(SessionLocaleResolver),基于cookie的配置(CookieLocaleResolver)
initLocaleResolver(context);
// 初始化 ThemeResolver:主要用来设置主题Theme
initThemeResolver(context);
// 初始化 HandlerMapping:映射器,用来将对应的request跟controller进行对应
initHandlerMappings(context);
// 初始化 HandlerAdapter:处理适配器,主要包含Http请求处理器适配器,简单控制器处理器适配器,注解方法处理器适配器
initHandlerAdapters(context);
// 初始化 HandlerExceptionResolver:基于HandlerExceptionResolver接口的异常处理
initHandlerExceptionResolvers(context);
// 初始化 RequestToViewNameTranslator:当controller处理器方法没有返回一个View对象或逻辑视图名称,并且在该方法中没有直接往response的输出流里面写数据的时候,spring将会采用约定好的方式提供一个逻辑视图名称
initRequestToViewNameTranslator(context);
// 初始化 ViewResolver: 将ModelAndView选择合适的视图进行渲染的处理器
initViewResolvers(context);
// 初始化 FlashMapManager: 提供请求存储属性,可供其他请求使用
initFlashMapManager(context);
}

链接

DispatcherServlet

Java Web项目中的一个配置文件

web.xml

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
<web-app>
<!-- Spring 配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<!-- org.springframework.web.context.ContextLoader#initWebApplicationContext -->
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-container.xml</param-value>
</context-param>

<!-- SpringMVC 配置-->
<servlet>
<servlet-name>app</servlet-name>
<!-- org.springframework.web.servlet.DispatcherServlet#init -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc-container.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
</web-app>

启动顺序

通过注册 Web 服务器的监听器 ContextLoaderListener, 加载 Spring 配置文件并启动;
在加载Servlet时, DispatcherServlet 引导 SpringMVC 启动;
通过启动 SpringMVC 事件加载内置组件(可覆盖 DispatcherServlet.properties 自定义配置)。

SpringBoot 中的顺序是不一样的, 是由Spring内嵌 使用 Spring 配置来引导自身和嵌入式 Servlet 容器。 Filter 和 Servlet 声明在 Spring 配置中检测到并在 Servlet 容器中注册。有关更多详细信息参阅 Spring 文档

链接

DispatcherServlet

简介

当踏上阅读 Spring MVC 源码的旅程,将迎来一场对框架内部运作的深入探索。通过阅读源码,将不仅加深对框架的理解,还能提升的编程技能。
在这个系列中,我们将从 DispatcherServlet 这个请求处理的入口点开始,会一步步深入的代码分析和注释解读,将能够更好地理解每个组件的作用和相互关系。

目录

SpringMVC 源码之启动

SpringMVC 源码之多个容器加载

SpringMVC 源码之加九大组件初始化

SpringMVC 源码之网络请求(1)

SpringMVC 源码之网络请求(2)

SpringMVC 源码之网络请求(3)

SpringMVC 源码之网络请求(4)

SpringMVC 源码之异步处理

SpringMVC 源码之常用接口

参考链接

官网
源码注释

1. 核心接口 BeanPostProcessor

1
2
3
public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

1.2 常用接口

1.2.1 BeanDefinitionRegistryPostProcessor

调用方法: PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

时机: BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry 会优先于 BeanPostProcessor #postProcessBeanFactory 方法的执行

作用: 所有 BeanDefinition 加载完成之后, 提供增删改查 BeanDefinitionRegistry (注册表) 的埋点

1.3 常用实现类

1.3.1 ConfigurationClassPostProcessor

作用: 它是用来解析配置类的, 可解析类注解 @Configuration, @CompentScan 等

2. 核心接口 BeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
public interface BeanPostProcessor {

default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}

}

2.2 常用接口

  1. SmartInstantiationAwareBeanPostProcessor
  2. MergedBeanDefinitionPostProcessor
  3. InstantiationAwareBeanPostProcessor
  4. DestructionAwareBeanPostProcessor

2.3 常用接口执行顺序

2.3.1 InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation

调用方法:AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation ===>>> #applyBeanPostProcessorsBeforeInstantiation

作用: 在实例化目标 bean 之前调用这个 BeanPostProcessor。返回的 bean 对象可以是一个代理来代替目标 bean,有效地抑制了目标 bean 的默认实例化。

2.3.2 SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors

调用方法:AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

作用: 检测Bean的构造器,可以检测出多个候选构造器,再有相应的策略决定使用哪一个,如AutowiredAnnotationBeanPostProcessor实现将自动扫描通过@Autowired/@Value注解的构造器从而可以完成构造器注入

2.3.3 MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition

调用方法: AbstractAutowireCapableBeanFactory#applyMergedBeanDefinitionPostProcessors

作用: 在Bean实例化完毕后调用 可以用来修改Merged BeanDefinition的一些properties 或者用来给后续回调中缓存一些meta信息, 这是将Merged BeanDefinition暴露出来的一个回调

2.3.4 SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference

调用方法: AbstractAutowireCapableBeanFactory#getEarlyBeanReference

作用: 获取早期访问指定 bean 的引用,通常用于解析循环引用。此回调使后处理器有机会尽早公开包装实例,即在目标 bean 实例完全初始化之前。

2.3.5 InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation

调用方法: AbstractAutowireCapableBeanFactory#populateBean

作用: 在 bean 实例化之后,通过构造函数或工厂方法,但在 Spring 属性填充(从显式属性或自动连接)发生之前,执行操作。这是在 Spring 的自动注入开始之前,在给定 bean 实例上执行自定义字段注入的回调。返回值可以终止属性填充。

2.3.6 InstantiationAwareBeanPostProcessor#postProcessProperties

调用方法: AbstractAutowireCapableBeanFactory#populateBean

作用: 在工厂将给定的属性值赋值到 bean 实例之前,对其进行后处理,而不需要任何属性描述符。

2.3.7 BeanPostProcessor#postProcessBeforeInitialization

调用方法: AbstractAutowireCapableBeanFactory#initializeBean ===>>> #applyBeanPostProcessorsBeforeInitialization

作用: 在任何 bean 初始化回调(如InitializingBean的AfterPropertieSet或自定义init方法)之前,将此BeanPostProcessor应用于给定的新bean实例。

2.3.8 InitializingBean#afterPropertiesSet

调用方法: AbstractAutowireCapableBeanFactory#invokeInitMethods

作用: bean 的初始化方法, 执行完成之后才会执行 自定义的 init 方法

2.3.9 BeanPostProcessor#postProcessAfterInitialization

调用方法: AbstractAutowireCapableBeanFactory#initializeBean ===>>> #applyBeanPostProcessorsAfterInitialization

作用: 在任何bean初始化回调(如InitializingBean的AfterPropertieSet或自定义init方法)之后,将此BeanPostProcessor应用于给定的新bean实例。

2.3.10 DestructionAwareBeanPostProcessor#postProcessBeforeDestruction

调用方法: AbstractAutowireCapableBeanFactory#destroyBean ===>>> DisposableBeanAdapter#destroy

作用: 在给定bean实例被销毁之前,将此BeanPostProcessor应用于该实例,例如调用自定义销毁回调。与DisposableBean的destroy和自定义destroy方法一样,此回调将仅适用于容器完全管理其生命周期的bean。单例bean和作用域bean通常都是这样。

2.3.10 DisposableBean#destroy

调用方法: AbstractAutowireCapableBeanFactory#destroyBean ===>>> DisposableBeanAdapter#destroy

作用: bean 的销毁方法, 执行完成之后才会执行自定义的 destroy 方法

2.4 接口无执行顺序

2.4.1 SmartInstantiationAwareBeanPostProcessor#predictBeanType

调用方法: AbstractAutowireCapableBeanFactory#predictBeanType

1
2
3
4
5
6
7
// AbstractApplicationContext#refresh
// ==> AbstractApplicationContext#registerListeners
// ==> AbstractApplicationContext#getBeanNamesForType
// ==> DefaultListableBeanFactory#doGetBeanNamesForType
// ==> AbstractAutowireCapableBeanFactory#predictBeanType
// 被此逻辑触发
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);

作用: 用来预判类型的

3. 接口 SmartInitializingSingleton

1
2
3
public interface SmartInitializingSingleton {
void afterSingletonsInstantiated();
}

3.1 org.springframework.beans.factory.SmartInitializingSingleton

调用方法: org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons

作用: 所有单例对象加载完成后调用,可以使用此接口回调处理逻辑

14 AbstractApplicationContext#destroyBeans

定位: org.springframework.context.support.AbstractApplicationContext#destroyBeans

1
2
3
4
5
6
7
8
9
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}

public void destroySingletons() {
super.destroySingletons();
updateManualSingletonNames(Set::clear, set -> !set.isEmpty());
clearByTypeCache();
}

15 AbstractApplicationContext#cancelRefresh

定位: org.springframework.context.support.AbstractApplicationContext#cancelRefresh

1
2
3
protected void cancelRefresh(BeansException ex) {
this.active.set(false);
}

16 AbstractApplicationContext#resetCommonCaches

定位: org.springframework.context.support.AbstractApplicationContext#resetCommonCaches

1
2
3
4
5
6
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}

13 AbstractApplicationContext#finishRefresh

定位: org.springframework.context.support.AbstractApplicationContext#finishRefresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清除资源缓存
clearResourceCaches();

// Initialize lifecycle processor for this context.
// 将刷新完毕时间传播到生命周期处理器
initLifecycleProcessor();

// Propagate refresh to lifecycle processor first.
// 首先将刷新完毕事件传播到生命周期处理器(触发 isAutoStartup 方法返回 true 的 SmartLifecycle#start 方法)
getLifecycleProcessor().onRefresh();

// Publish the final event.
// 发布事件
publishEvent(new ContextRefreshedEvent(this));

// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}

13.1 AbstractApplicationContext#initLifecycleProcessor

定位: org.springframework.context.support.AbstractApplicationContext#finishRefresh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断 beanFactory 是否已经存在生命周期处理器
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
// 如果已经存在,则将该bean赋值给lifecycleProcessor
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
// 如果不存在,则使用 DefaultLifecycleProcessor
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
// 将 DefaultLifecycleProcessor 作为默认的生命周期处理器,注册到 beanFactory 中
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}

13.2 DefaultLifecycleProcessor#onRefresh

定位: org.springframework.context.support.DefaultLifecycleProcessor#onRefresh

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
// org.springframework.context.support.DefaultLifecycleProcessor#onRefresh
public void onRefresh() {
startBeans(true);
this.running = true;
}

private void startBeans(boolean autoStartupOnly) {
// 检索所有适用的生命周期Bean:所有已经创建的单例Bean,以及所有 SmartLifeCycle Bean(即使它们被标记未延迟初始化)
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
// 各 phases 所对应的 LifecycleGroup Map
Map<Integer, LifecycleGroup> phases = new HashMap<>();
// 遍历所有 lifecycle bean,按阶段值分组
lifecycleBeans.forEach((beanName, bean) -> {
// SmartLifecycle : 生命周期接口的扩展,用于那些需要在 ApplicationContext 刷新 和/或 特定顺序关闭时 启动的对象。
// 如果不是 autoStartupOnly || (bean 是 SmartLifecycle 的实例) && bean指定在包含ApplicationContext的刷新时由容器自动启动
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
// 获取 bean 的生命周期阶段(相位值)
int phase = getPhase(bean);
// 获取 phase 对应的 LifecycleGroup
LifecycleGroup group = phases.get(phase);
// 如果 group 不为 null
if (group == null) {
// 新建一个 LifecycleGroup 的实例
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
//将 phase,group 绑定到 phases 中
phases.put(phase, group);
}
// 将beanName,bean绑定到 group 中
group.add(beanName, bean);
}
});
// 如果 phases 不是空集
if (!phases.isEmpty()) {
// 存放生命周期阶段(相位值)
List<Integer> keys = new ArrayList<>(phases.keySet());
// 按阶段值进行排序
Collections.sort(keys);
// 调用 lifecycleGroup 中的所有 lifecycle#start 方法
for (Integer key : keys) {
// 启动 key 对应的 LifecycleGroup
phases.get(key).start();
}
}
}

13.3 AbstractApplicationContext#publishEvent

定位: org.springframework.context.support.AbstractApplicationContext#publishEvent

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
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");

// Decorate event as an ApplicationEvent if necessary
// 如果有必要,将事件装饰为 applicationEvent
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
// 不是事件类型就转为事件类型
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}

// Multicast right now if possible - or lazily once the multicaster is initialized
// 如果可能,立即进行多播或者一旦初始化多播器就进入懒惰状态
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
// 获取事件广播器,发布事件
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}

// Publish event via parent context as well...
// 如果存在父容器,那么父容器也发布事件
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
}

13.3.1 SimpleApplicationEventMulticaster#multicastEvent

定位: org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent

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
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
// 返回此广播器的当前任务执行程序
Executor executor = getTaskExecutor();
// getApplicationListeners方法是返回与给定事件类型匹配的应用监听器集合
// 遍历所有的监听器
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null) {
// 如果executor不为空,则使用executor调用监听器
executor.execute(() -> invokeListener(listener, event));
}
else {
// 否则直接调用监听器
invokeListener(listener, event);
}
}
}

protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
// 返回此广播器的当前错误处理程序
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
// 如果errorHandler不为null,则使用带错误处理的方式调用给定的监听器
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
// 否则直接调用给定的监听器
doInvokeListener(listener, event);
}
}

private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
// 触发监听器的onApplicationEvent方法,参数为给定的事件
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isTraceEnabled()) {
logger.trace("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}

12.2 AbstractAutowireCapableBeanFactory#createBean

定位: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])

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
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

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

// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// 锁定class,根据设置的class属性或者根据className来解析class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
// 进行条件筛选,重新赋值RootBeanDefinition,并设置BeanClass属性
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// 重新创建一个RootBeanDefinition对象
mbdToUse = new RootBeanDefinition(mbd);
// 设置BeanClass属性值
mbdToUse.setBeanClass(resolvedClass);
}

// Prepare method overrides.
// 验证及准备覆盖的方法,lookup-method replace-method,
// 当需要创建的bean对象中包含了lookup-method和replace-method标签的时候,会产生覆盖操作
try {
// 验证以及准备覆盖的方法即Override方法
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 返回代理来代替真正的实例:--------------应用实例化前的前置处理器
// 给BeanPostProcessors一个机会来返回代理来替代真正的实例,应用实例化前的前置处理器
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}

try {
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);
}
}

12.2.1 AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 如果beforeInstantiationResolved值为null或者true,那么表示尚未被处理,进行后续的处理
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
// 确认beanClass确实在此处进行处理
// 判断当前mbd是否是合成的,只有在实现aop的时候synthetic的值才为true,
// 并且是否实现了InstantiationAwareBeanPostProcessor接口
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 获取类型
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
// 是否解析了
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}

12.2.2 AbstractAutowireCapableBeanFactory#doCreateBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

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
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {

// Instantiate the bean.
// 这个beanWrapper是用来持有创建出来的bean对象的
BeanWrapper instanceWrapper = null;
// 获取factoryBean实例缓存
if (mbd.isSingleton()) {
// 如果是单例对象,从factorybean实例缓存中移除当前bean定义信息
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 没有就创建实例
if (instanceWrapper == null) {
// 创建Bean对象,并且将对象包裹在 BeanWrapper 中
// 根据执行bean使用对应的策略创建新的实例,如,工厂方法,构造函数主动注入、简单初始化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 再从Wrapper中把Bean原始对象(非代理) 这个时候这个Bean就有地址值了,就能被引用了
final Object bean = instanceWrapper.getWrappedInstance();
// 获取具体的bean对象的Class属性
Class<?> beanType = instanceWrapper.getWrappedClass();
// 如果不等于NullBean类型,那么修改目标类型
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

// Allow post-processors to modify the merged bean definition.
// 允许 beanPostProcessor 去修改合并的 beanDefinition
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// MergedBeanDefinitionPostProcessor 后置处理器修改合并bean的定义
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 判断当前bean是否需要提前曝光:单例&允许循环依赖&当前bean正在创建中,检测循环依赖
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初始化完成前将创建实例的ObjectFactory加入工厂
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
// 初始化bean实例
Object exposedObject = bean;
try {
// 使用Bean定义中的属性值填充给定BeanWrapper中的Bean实例
// 对bean的属性进行填充,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean
populateBean(beanName, mbd, instanceWrapper);
// 使用工厂回调以及初始化方法和bean后处理器初始化给定的bean实例。执行初始化逻辑
// 1. BeanNameAware#setBeanName、BeanClassLoaderAware#setBeanClassLoader、BeanFactoryAware#setBeanFactory
// 2. BeanPostProcessor#postProcessBeforeInitialization
// 3. InitializingBean#afterPropertiesSet 和 调用配置的 initMethod 方法
// 4. BeanPostProcessor#postProcessAfterInitialization
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) {
// 尝试从缓存中获取单例,注意后面的参数为false,表示不从第三级缓存singletonFactories中获取
// 为什么呢?因为这里不允许循环依赖
Object earlySingletonReference = getSingleton(beanName, false);
// 如果不为null,就会进入if条件中,因为earlySingletonReference不为null,说明存在循环引用,
// 为什么呢?因为第一个处理的时候,会将引用放到singletonFactories缓存中,当循环依赖注入的时候,
// 会通过singletonFactories中拿到提前暴露的引用,然后放到第二级缓存earlySingletonObjects中。
// 所以,在这里拿到了earlySingletonReference,表明存在循环引用。
// earlySingletonReference只有在检测到有循环依赖的情况下才会不为空
if (earlySingletonReference != null) {
// 如果相等,那么就什么也不做,将earlySingletonReference返回回去即可
// 如果exposedObject没有在初始化方法中被改变,也就是没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
// 如果不相等,并且有其它bean依赖这个bean
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 拿到依赖这个bean的所有bean
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 如果存在已经创建完的bean(已经创建完的bean依赖该bean)
// 返回false说明依赖还没实例化好
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
// 防止对象被改变,造成的已创建对象中持有的对象和这个对象不一致。
// 因为bean创建后所依赖的bean一定是已经创建的
// actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有全部创建完,也就是说存在循环依赖
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.");
}
}
}
}

// Register bean as disposable.
try {
// 注册 DisposableBean 和 解析配置的 destroyMethod 方法
// 注册bean对象,方便后续在容器销毁的时候销毁对象
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}

12.2.2.1 AbstractAutowireCapableBeanFactory#createBeanInstance

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance

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
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 确认需要创建的bean实例的类可以实例化
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());
}

// 判断当前beanDefinition中是否包含实例供应器,此处相当于一个回调方法,利用回调方法来创建bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

// 如果工厂方法不为空则使用工厂方法初始化策略
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

// 一个类可能有多个构造器,所以Spring得根据参数个数、类型确定需要调用的构造器
// 在使用构造器创建实例后,Spring会将解析过后确定下来的构造器或工厂方法保存在缓存中,避免再次创建相同bean时再次解析

// Shortcut when re-creating the same bean...
// 标记下,防止重复创建同一个bean
boolean resolved = false;
// 是否需要自动装配
boolean autowireNecessary = false;
// 如果没有参数
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 因为一个类可能由多个构造函数,所以需要根据配置文件中配置的参数或传入的参数来确定最终调用的构造函数。
// 因为判断过程会比较,所以spring会将解析、确定好的构造函数缓存到BeanDefinition中的resolvedConstructorOrFactoryMethod字段中。
// 在下次创建相同时直接从RootBeanDefinition中的属性resolvedConstructorOrFactoryMethod缓存的值获取,避免再次解析
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 有构造参数的或者工厂方法
if (resolved) {
// 构造器有参数
if (autowireNecessary) {
// 构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认构造函数构造
return instantiateBean(beanName, mbd);
}
}

// Candidate constructors for autowiring?
// 从bean后置处理器中为自动装配寻找构造方法, 有且仅有一个有参构造或者有且仅有@Autowired注解构造
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 以下情况符合其一即可进入
// 1、存在可选构造方法
// 2、自动装配模型为构造函数自动装配
// 3、给BeanDefinition中设置了构造参数值
// 4、有参与构造函数参数列表的参数
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}

// Preferred constructors for default construction?
// 找出最合适的默认构造方法
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}

// No special handling: simply use no-arg constructor.
// 使用默认无参构造函数创建对象,如果没有无参构造且存在多个有参构造且没有@AutoWired注解构造,会报错
return instantiateBean(beanName, mbd);
}

12.2.2.1.1 ConstructorResolver#autowireConstructor

**定位: ** org.springframework.beans.factory.support.ConstructorResolver#autowireConstructor

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
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {

// 实例化BeanWrapper。是包装bean的容器
BeanWrapperImpl bw = new BeanWrapperImpl();
// 给包装对象设置一些属性
this.beanFactory.initBeanWrapper(bw);

// spring对这个bean进行实例化使用的构造函数
Constructor<?> constructorToUse = null;
// spring执行构造函数使用的是参数封装类
ArgumentsHolder argsHolderToUse = null;
// 参与构造函数实例化过程的参数
Object[] argsToUse = null;

// 如果传入参数的话,就直接使用传入的参数
if (explicitArgs != null) {
// 让argsToUse引用explicitArgs
argsToUse = explicitArgs;
}
// 没有传入参数的话就走else
else {
//声明一个要解析的参数值数组,默认为null
Object[] argsToResolve = null;
synchronized (mbd.constructorArgumentLock) {
// 获取BeanDefinition中解析完成的构造函数
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
// BeanDefinition中存在构造函数并且存在构造函数的参数,赋值进行使用
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
// Found a cached constructor...
// 从缓存中找到了构造器,那么继续从缓存中寻找缓存的构造器参数
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {
// 没有缓存的参数,就需要获取配置文件中配置的参数
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
// 如果缓存中没有缓存的参数的话,即argsToResolve不为空,就需要解析配置的参数
if (argsToResolve != null) {
// 解析参数类型,比如将配置的String类型转换为list、boolean等类型
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
}
}

// 如果constructorToUse为null或者argsToUser为null
if (constructorToUse == null || argsToUse == null) {
// Take specified constructors, if any.
// 如果传入的构造器数组不为空,就使用传入的过后早期参数,否则通过反射获取class中定义的构造器
Constructor<?>[] candidates = chosenCtors;
// 如果candidates为null
if (candidates == null) {
// 获取mbd的Bean类
Class<?> beanClass = mbd.getBeanClass();
try {
// 使用public的构造器或者所有构造器
candidates = (mbd.isNonPublicAccessAllowed() ?
beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
// 捕捉获取beanClass的构造函数发出的异常
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}

// 如果candidateList只有一个元素 且 没有传入构造函数值 且 mbd也没有构造函数参数值
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
// 获取candidates中唯一的方法
Constructor<?> uniqueCandidate = candidates[0];
// 如果uniqueCandidate不需要参数
if (uniqueCandidate.getParameterCount() == 0) {
// 使用mdb的构造函数字段的通用锁【{@link RootBeanDefinition#constructorArgumentLock}】进行加锁以保证线程安全
synchronized (mbd.constructorArgumentLock) {
// 让mbd缓存已解析的构造函数或工厂方法
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
// 让mbd标记构造函数参数已解析
mbd.constructorArgumentsResolved = true;
// 让mbd缓存完全解析的构造函数参数
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// 使用constructorToUse生成与beanName对应的Bean对象,并将该Bean对象保存到bw中
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
// 将bw返回出去
return bw;
}
}

// Need to resolve the constructor.
// 自动装配标识,以下有一种情况成立则为true,
// 1、传进来构造函数,证明spring根据之前代码的判断,知道应该用哪个构造函数,
// 2、BeanDefinition中设置为构造函数注入模型
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
// 定义一个用于存放解析后的构造函数参数值的ConstructorArgumentValues对象
ConstructorArgumentValues resolvedValues = null;

// 构造函数的最小参数个数
int minNrOfArgs;
// 如果传入了参与构造函数实例化的参数值,那么参数的数量即为最小参数个数
if (explicitArgs != null) {
// minNrOfArgs引用 explicitArgs 的数组长度
minNrOfArgs = explicitArgs.length;
}
else {
// 提取配置文件中的配置的构造函数参数
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
// 用于承载解析后的构造函数参数的值
resolvedValues = new ConstructorArgumentValues();
// 能解析到的参数个数
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}

// 对候选的构造函数进行排序,先是访问权限后是参数个数
// public权限参数数量由多到少
AutowireUtils.sortConstructors(candidates);
// 定义一个差异变量,变量的大小决定着构造函数是否能够被使用
int minTypeDiffWeight = Integer.MAX_VALUE;
// 不明确的构造函数集合,正常情况下差异值不可能相同
Set<Constructor<?>> ambiguousConstructors = null;
// 定义一个用于UnsatisfiedDependencyException的列表
LinkedList<UnsatisfiedDependencyException> causes = null;

// 循环候选的构造函数
for (Constructor<?> candidate : candidates) {
// 获取参数的个数
Class<?>[] paramTypes = candidate.getParameterTypes();

// 如果已经找到选用的构造函数或者需要的参数个数小于当前的构造函数参数个数则终止,前面已经经过了排序操作
if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
// Already found greedy constructor that can be satisfied ->
// do not look any further, there are only less greedy constructors left.
break;
}
// 如果本构造函数的参数列表数量小于要求的最小数量,则遍历下一个
if (paramTypes.length < minNrOfArgs) {
// 参数个数不相等
continue;
}

// 存放构造函数解析完成的参数列表
ArgumentsHolder argsHolder;
// 存在需要解析的构造函数参数
if (resolvedValues != null) {
try {
// 获取构造函数上的ConstructorProperties注解中的参数
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
// 如果没有上面的注解,则获取构造函数参数列表中属性的名称
if (paramNames == null) {
// 获取参数名称探索器
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
// 获取指定构造函数的参数名称
paramNames = pnd.getParameterNames(candidate);
}
}
// 根据名称和数据类型创建参数持有者
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
// 吞下并尝试下一个重载的构造函数
// 如果cause为null
if (causes == null) {
// 对cause进行实例化成LinkedList对象
causes = new LinkedList<>();
}
// 将ex添加到causes中
causes.add(ex);
continue;
}
}
// 不存在构造函数参数列表需要解析的参数
else {
// Explicit arguments given -> arguments length must match exactly.
// 如果参数列表的数量与传入进来的参数数量不相等,继续遍历,否则构造参数列表封装对象
if (paramTypes.length != explicitArgs.length) {
continue;
}
// 构造函数没有参数的情况
argsHolder = new ArgumentsHolder(explicitArgs);
}

// 计算差异量,根据要参与构造函数的参数列表和本构造函数的参数列表进行计算
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// Choose this constructor if it represents the closest match.
// 本次的构造函数差异值小于上一个构造函数,则进行构造函数更换
if (typeDiffWeight < minTypeDiffWeight) {
// 将确定使用的构造函数设置为本构造
constructorToUse = candidate;
// 更换使用的构造函数参数封装类
argsHolderToUse = argsHolder;
// 更换参与构造函数实例化的参数
argsToUse = argsHolder.arguments;
// 差异值更换
minTypeDiffWeight = typeDiffWeight;
// 不明确的构造函数列表清空为null
ambiguousConstructors = null;
}
// 差异值相等,则表明构造函数不正常,放入异常集合
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
// 如果ambiguousFactoryMethods为null
if (ambiguousConstructors == null) {
// 初始化ambiguousFactoryMethods为LinkedHashSet实例
ambiguousConstructors = new LinkedHashSet<>();
// 将constructorToUse添加到ambiguousFactoryMethods中
ambiguousConstructors.add(constructorToUse);
}
// 将candidate添加到ambiguousFactoryMethods中
ambiguousConstructors.add(candidate);
}
}

// 以下两种情况会抛异常
// 1、没有确定使用的构造函数
// 2、存在模糊的构造函数并且不允许存在模糊的构造函数
if (constructorToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
this.beanFactory.onSuppressedException(cause);
}
throw ex;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
}
else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors);
}

/*
* 没有传入参与构造函数参数列表的参数时,对构造函数缓存到BeanDefinition中
* 1、缓存BeanDefinition进行实例化时使用的构造函数
* 2、缓存BeanDefinition代表的Bean的构造函数已解析完标识
* 3、缓存参与构造函数参数列表值的参数列表
*/
if (explicitArgs == null && argsHolderToUse != null) {
// 将解析的构造函数加入缓存
argsHolderToUse.storeCache(mbd, constructorToUse);
}
}

Assert.state(argsToUse != null, "Unresolved constructor arguments");
// 将构造的实例加入BeanWrapper中
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}

12.2.2.1.2 AbstractAutowireCapableBeanFactory#instantiateBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
// 获取实例化策略并且进行实例化操作
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
// 包装成BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}

12.2.2.1.3 AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {

if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
// 从SmartInstantiationAwareBeanPostProcessor判断
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}

12.2.2.2 DefaultSingletonBeanRegistry#addSingletonFactory

**定位: ** org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
// 放到单例工厂里
this.singletonFactories.put(beanName, singletonFactory);
// 删除早期单例
this.earlySingletonObjects.remove(beanName);
// 添加到已注册
this.registeredSingletons.add(beanName);
}
}
}

12.2.2.3 AbstractAutowireCapableBeanFactory#populateBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean

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
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 如果beanWrapper为空
if (bw == null) {
// 如果mbd有需要设置的属性
if (mbd.hasPropertyValues()) {
// 抛出bean创建异常
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
// 没有可填充的属性,直接跳过
return;
}
}

// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// 给任何实现了InstantiationAwareBeanPostProcessors的子类机会去修改bean的状态再设置属性之前,可以被用来支持类型的字段注入

// 否是"synthetic"。一般是指只有AOP相关的pointCut配置或者Advice配置才会将 synthetic设置为true
// 如果mdb是不是'synthetic' 且 工厂拥有InstantiationAwareBeanPostProcessor
boolean continueWithPropertyPopulation = true;

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 遍历工厂中的BeanPostProcessor对象
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果 bp 是 InstantiationAwareBeanPostProcessor 实例
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// postProcessAfterInstantiation:一般用于设置属性
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}

if (!continueWithPropertyPopulation) {
return;
}

// PropertyValues:包含以一个或多个PropertyValue对象的容器,通常包括针对特定目标Bean的一次更新
// 如果mdb有PropertyValues就获取其PropertyValues
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

// 获取 mbd 的 自动装配模式
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// 如果 自动装配模式 为 按名称自动装配bean属性 或者 按类型自动装配bean属性
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// MutablePropertyValues:PropertyValues接口的默认实现。允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
// 根据autotowire的名称(如适用)添加属性值
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
// 通过bw的PropertyDescriptor属性名,查找出对应的Bean对象,将其添加到newPvs中
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
// 根据自动装配的类型(如果适用)添加属性值
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到newPvs中
autowireByType(beanName, mbd, bw, newPvs);
}
// 让pvs重新引用newPvs,newPvs此时已经包含了pvs的属性值以及通过AUTOWIRE_BY_NAME,AUTOWIRE_BY_TYPE自动装配所得到的属性值
pvs = newPvs;
}

//工厂是否拥有InstantiationAwareBeanPostProcessor
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// mbd.getDependencyCheck(),默认返回 DEPENDENCY_CHECK_NONE,表示 不检查
// 是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

// 经过筛选的PropertyDescriptor数组,存放着排除忽略的依赖项或忽略项上的定义的属性
PropertyDescriptor[] filteredPds = null;
// 如果工厂拥有InstantiationAwareBeanPostProcessor,那么处理对应的流程,主要是对几个注解的赋值工作包含的两个关键子类是CommonAnnoationBeanPostProcessor,AutowiredAnnotationBeanPostProcessor
if (hasInstAwareBpps) {
if (pvs == null) {
// 尝试获取mbd的PropertyValues
pvs = mbd.getPropertyValues();
}
// 遍历工厂内的所有后置处理器
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果 bp 是 InstantiationAwareBeanPostProcessor 的实例
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 将 bp 强转成 InstantiationAwareBeanPostProcessor 对象
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// postProcessProperties:在工厂将给定的属性值应用到给定Bean之前,对它们进行后处理,不需要任何属性扫描符。该回调方法在未来的版本会被删掉。
// -- 取而代之的是 postProcessPropertyValues 回调方法。
// 让ibp对pvs增加对bw的Bean对象的propertyValue,或编辑pvs的propertyValue
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
// mbd.allowCaching:是否允许缓存,默认时允许的。缓存除了可以提高效率以外,还可以保证在并发的情况下,返回的PropertyDesciptor[]永远都是同一份
// 从bw提取一组经过筛选的PropertyDescriptor,排除忽略的依赖项或忽略项上的定义的属性
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// postProcessPropertyValues:一般进行检查是否所有依赖项都满足,例如基于"Require"注释在 bean属性 setter,
// -- 替换要应用的属性值,通常是通过基于原始的PropertyValues创建一个新的MutablePropertyValue实例, 添加或删除特定的值
// -- 返回的PropertyValues 将应用于bw包装的bean实例 的实际属性值(添加PropertyValues实例到pvs 或者 设置为null以跳过属性填充)
// 回到ipd的postProcessPropertyValues方法
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
// 如果pvsToUse为null,将终止该方法精致,以跳过属性填充
if (pvsToUse == null) {
return;
}
}
// 让pvs引用pvsToUse
pvs = pvsToUse;
}
}
}
// 如果需要依赖检查
if (needsDepCheck) {
if (filteredPds == null) {
// 从bw提取一组经过筛选的PropertyDescriptor,排除忽略的依赖项或忽略项上的定义的属性
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 检查依赖项:主要检查pd的setter方法需要赋值时,pvs中有没有满足其pd的需求的属性值可供其赋值
checkDependencies(beanName, mbd, filteredPds, pvs);
}

if (pvs != null) {
// 应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 不会永久地修改这个属性
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
12.2.2.3.1 AbstractAutowireCapableBeanFactory#autowireByName

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByName

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
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

// 获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历属性名
for (String propertyName : propertyNames) {
// 如果该bean工厂有propertyName的beanDefinition或外部注册的singleton实例
if (containsBean(propertyName)) {
// 获取该工厂中propertyName的bean对象
Object bean = getBean(propertyName);
// 将propertyName,bean添加到pvs中
pvs.add(propertyName, bean);
// 注册propertyName与beanName的依赖关系
registerDependentBean(propertyName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
12.2.2.3.2 AbstractAutowireCapableBeanFactory#autowireByType

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByType

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
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

// 获取工厂的自定义类型转换器
TypeConverter converter = getCustomTypeConverter();
// 如果没有配置自定义类型转换器
if (converter == null) {
// 使用bw作为类型转换器
converter = bw;
}

// 存放所有候选Bean名的集合
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
// 获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历属性名数组
for (String propertyName : propertyNames) {
try {
// PropertyDescriptor:表示JavaBean类通过存储器导出一个属性
// 从bw中获取propertyName对应的PropertyDescriptor
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
// 不要尝试按类型自动装配对象:永远是有意义的,即使它在技术上是一个不满意,复杂属性
// 如果pd的属性值类型不是 Object
if (Object.class != pd.getPropertyType()) {
// 获取pd属性的Setter方法的方法参数包装对象
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
// 判断bean对象是否是PriorityOrder实例,如果不是就允许急于初始化来进行类型匹配。
// eager为true时会导致初始化lazy-init单例和由FactoryBeans(或带有"factory-bean"引用的工厂方法)创建 的对象以进行类型检查
boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
// AutowireByTypeDependencyDescriptor:根据类型依赖自动注入的描述符,重写了 getDependencyName() 方法,使其永远返回null
// 将 methodParam 封装包装成AutowireByTypeDependencyDescriptor对象
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 根据据desc的依赖类型解析出与descriptor所包装的对象匹配的候选Bean对象
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
// 如果autowiredArgument不为null
if (autowiredArgument != null) {
// 将propertyName.autowiredArgument作为键值添加到pvs中
pvs.add(propertyName, autowiredArgument);
}
// 遍历所有候选Bean名集合
for (String autowiredBeanName : autowiredBeanNames) {
// 注册beanName与dependentBeanNamed的依赖关系
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
// 将候选Bean名集合清空
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
// 捕捉自动装配时抛出的Bean异常,重新抛出 不满足依赖异常
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
12.2.2.3.3 AbstractAutowireCapableBeanFactory#applyPropertyValues

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues

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
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) {
return;
}

// 如果有安全管理器,且bw是BeanWrapperImpl的实例
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
// 设置bw的安全上下文为工厂的访问控制上下文
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}

// MutablePropertyValues:PropertyValues接口的默认实现。
// 允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造
MutablePropertyValues mpvs = null;
// 原始属性列表
List<PropertyValue> original;

// 如果pvs是MutablePropertyValues
if (pvs instanceof MutablePropertyValues) {
// 类型强制转换
mpvs = (MutablePropertyValues) pvs;
// isConverted:返回该holder是否只包含转换后的值(true),或者是否仍然需要转换这些值
// 如果mpvs只包含转换后的值
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
// 已完成,直接返回
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
//捕捉Bean异常,重新抛出Bean创佳异常:错误设置属性值。
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
// 获取mpvs的PropertyValue列表
original = mpvs.getPropertyValueList();
}
else {
// 获取pvs的PropertyValue对象数组,并将其转换成列表
original = Arrays.asList(pvs.getPropertyValues());
}

// 获取用户自定义类型转换器
TypeConverter converter = getCustomTypeConverter();
// 如果转换器为空,则直接把包装类赋值给converter
if (converter == null) {
converter = bw;
}
// BeanDefinitionValueResolver:在bean工厂实现中使用Helper类,它将beanDefinition对象中包含的值解析为应用于 目标bean实例的实际值
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

// Create a deep copy, resolving any references for values.
// 创建一个深拷贝,解析任何值引用
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
//是否还需要解析标记
boolean resolveNecessary = false;
// 遍历属性,将属性转换为对应类的对应属性的类型
for (PropertyValue pv : original) {
// 如果该属性已经解析过
if (pv.isConverted()) {
// 将pv添加到deepCopy中
deepCopy.add(pv);
}
// 如果属性没有被解析过
else {
// 获取属性的名字
String propertyName = pv.getName();
// 获取未经类型转换的值
Object originalValue = pv.getValue();
// AutowiredPropertyMarker.INSTANCE:自动生成标记的规范实例
if (originalValue == AutowiredPropertyMarker.INSTANCE) {
// 获取propertyName在bw中的setter方法
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
// 如果setter方法为null
if (writeMethod == null) {
// 抛出非法参数异常:自动装配标记属性没有写方法。
throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
}
// 将writerMethod封装到DependencyDescriptor对象
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
// 交由valueResolver根据pv解析出originalValue所封装的对象
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
// 默认转换后的值是刚解析出来的值
Object convertedValue = resolvedValue;
// 可转换标记: propertyName是否bw中的可写属性 && prepertyName不是表示索引属性或嵌套属性(如果propertyName中有'.'||'['就认为是索引属性或嵌套属性)
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
// 如果可转换
if (convertible) {
// 将resolvedValue转换为指定的目标属性对象
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
// 可以将转换后的值存储合并后BeanDefinition中,以避免对每个创建的Bean实例进行重新转换
// 如果resolvedValue与originalValue是同一个对象
if (resolvedValue == originalValue) {
// 如果可转换
if (convertible) {
// 将convertedValue设置到pv中
pv.setConvertedValue(convertedValue);
}
// 将pv添加到deepCopy中
deepCopy.add(pv);
}
// TypedStringValue:类型字符串的Holder,这个holder将只存储字符串值和目标类型。实际得转换将由Bean工厂执行
// 如果可转换 && originalValue是TypedStringValue的实例 && orginalValue不是标记为动态【即不是一个表达式】&&
// convertedValue不是Collection对象 或 数组
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
// 将convertedValue设置到pv中
pv.setConvertedValue(convertedValue);
// 将pv添加到deepCopy中
deepCopy.add(pv);
}
else {
// 标记还需要解析
resolveNecessary = true;
// 根据pv,convertedValue构建PropertyValue对象,并添加到deepCopy中
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
// mpvs不为null && 已经不需要解析
if (mpvs != null && !resolveNecessary) {
// 将此holder标记为只包含转换后的值
mpvs.setConverted();
}

// Set our (possibly massaged) deep copy.
try {
// 按原样使用deepCopy构造一个新的MutablePropertyValues对象然后设置到bw中以对bw的属性值更新
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}

12.2.2.4 AbstractAutowireCapableBeanFactory#initializeBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean

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
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// Aware接口处理器, 调用 BeanNameAware#setBeanName、BeanClassLoaderAware#setBeanClassLoader、BeanFactoryAware#setBeanFactory
if (System.getSecurityManager() != null) {
// 以特权的方式执行回调bean中的Aware接口方法
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}

// 调用 BeanPostProcessor#postProcessBeforeInitialization
Object wrappedBean = bean;
// 如果mdb不为null || mbd不是"synthetic"。一般是指只有AOP相关的prointCut配置或者Advice配置才会将 synthetic设置为true
if (mbd == null || !mbd.isSynthetic()) {
// 将BeanPostProcessors应用到给定的现有Bean实例,调用它们的postProcessBeforeInitialization初始化方法。
// 返回的Bean实例可能是原始Bean包装器
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

// 调用 InitializingBean#afterPropertiesSet
// 反射调用配置的 initMethod 方法
try {
// 调用初始化方法,先调用bean的InitializingBean接口方法,后调用bean的自定义初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
// 调用 BeanPostProcessor#postProcessAfterInitialization
if (mbd == null || !mbd.isSynthetic()) {
// 将BeanPostProcessors应用到给定的现有Bean实例,调用它们的postProcessAfterInitialization方法。
// 返回的Bean实例可能是原始Bean包装器
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

// 返回包装后的Bean
return wrappedBean;
}
12.2.2.4.1 AbstractAutowireCapableBeanFactory#invokeAwareMethods

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
12.2.2.4.2 AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {

// 初始化返回结果为existingBean
Object result = existingBean;
// 遍历该工厂创建的bean的BeanPostProcessors列表
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// postProcessBeforeInitialization:在任何Bean初始化回调之前(如初始化Bean的afterPropertiesSet或自定义的init方法)
// 将此BeanPostProcessor 应用到给定的新Bean实例。Bean已经填充了属性值。返回的Bean实例可能时原始Bean的包装器。
// 默认实现按原样返回给定的 Bean
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
// 直接返回result,中断其后续的BeanPostProcessor处理
return result;
}
// 让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
result = current;
}
// 返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
return result;
}
12.2.2.4.2 AbstractAutowireCapableBeanFactory#invokeInitMethods

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods

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
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {

// isInitializingBean:当Bean的所有属性都被BeanFactory设置好后,Bean需要执行相应的接口:例如执行自定义初始化,或者仅仅是检查所有强制属性是否已经设置好。
// bean是InitializingBean实例标记
boolean isInitializingBean = (bean instanceof InitializingBean);
// isExternallyManagedInitMethod是否外部受管理的Init方法名
// 如果 bean是InitializingBean实例 && (mdb为null || 'afterPropertiesSet' 不是外部受管理的Init方法名)
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
// 以特权方式调用 bean的 afterPropertiesSet 方法
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 调用 bean 的 afterPropertiesSet 方法
((InitializingBean) bean).afterPropertiesSet();
}
}

// 如果mbd不为null && bean不是NullBean类
if (mbd != null && bean.getClass() != NullBean.class) {
// 获取mbd指定的初始化方法名
String initMethodName = mbd.getInitMethodName();
// 如果initMethodName不为null && (bean不是InitializingBean实例 && 'afterPropertiesSet'是初始化方法名)
// && initMethodName不是外部受管理的Init方法名
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 在bean上调用指定的自定义init方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}

protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {

// 获取初始化方法名称
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
// 获取初始化方法
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

if (initMethod == null) {
if (mbd.isEnforceInitMethod()) {
throw new BeanDefinitionValidationException("Could not find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
}
else {
if (logger.isTraceEnabled()) {
logger.trace("No default init method named '" + initMethodName +
"' found on bean with name '" + beanName + "'");
}
// Ignore non-existent default lifecycle methods.
return;
}
}

if (logger.isTraceEnabled()) {
logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
}
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);

if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(methodToInvoke);
return null;
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
methodToInvoke.invoke(bean), getAccessControlContext());
}
catch (PrivilegedActionException pae) {
InvocationTargetException ex = (InvocationTargetException) pae.getException();
throw ex.getTargetException();
}
}
else {
try {
ReflectionUtils.makeAccessible(methodToInvoke);
// 反射执行
methodToInvoke.invoke(bean);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
12.2.2.4.3 AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {

// 初始化结果对象为result,默认引用existingBean
Object result = existingBean;
// 遍历该工厂创建的bean的BeanPostProcessors列表
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// 回调BeanPostProcessor#postProcessAfterInitialization来对现有的bean实例进行包装
Object current = processor.postProcessAfterInitialization(result, beanName);
// 一般processor对不感兴趣的bean会回调直接返回result,使其能继续回调后续的BeanPostProcessor;
// 但有些processor会返回null来中断其后续的BeanPostProcessor
if (current == null) {
// 如果current为null,直接返回result,中断其后续的BeanPostProcessor处理
return result;
}
// 让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
result = current;
}
// 返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
return result;
}

12.2.2.5 AbstractAutowireCapableBeanFactory#registerDisposableBeanIfNecessary

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#registerDisposableBeanIfNecessary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
// 有销毁接口
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
// 单例的情况,注册销毁回调
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
// 自定义的,注册Scope
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}

11.finishBeanFactoryInitialization

定位: org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization

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
/**
* 完成此上下文的beanFactory的初始化,初始化所有剩余的单例对象。
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// beanFactory 初始化 conversionService (类型转换器)
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));
}


// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
// 如果没有embedded的后置处理器, 则注册一个默认的embedded后置处理器。 主要用于解析注解属性值
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}

// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 尽早初始化LoadTimeWeaverAware Bean,以便尽早注册其转换器。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}

// Stop using the temporary ClassLoader for type matching.
// 清空临时ClassLoader (禁止使用临时类加载器进行类型匹配)
beanFactory.setTempClassLoader(null);

// Allow for caching all bean definition metadata, not expecting further changes.
// 冻结所有的beanDefinition的metadata,不期被进一步的修改。
beanFactory.freezeConfiguration();

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

11.1 DefaultListableBeanFactory#preInstantiateSingletons

定位: org.springframework.beans.factory.support.DefaultListableBeanFactory#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
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
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}

// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
// 遍历一个副本以允许使用init方法,这些方法依次注册新的bean定义。
// 尽管这可能不是常规工厂引导程序的一部分,但可以正常运行。
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

// Trigger initialization of all non-lazy singleton beans...
// 触发初始化所有非懒加载单例bean
for (String beanName : beanNames) {
// 如果指定的bean对应一个子bean定义,遍历父BeanDefinition并合并成RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// RootBeanDefinition 不是抽象的、是单例的、不是懒加载的bean
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 是否是FactoryBean
if (isFactoryBean(beanName)) {
// 返回 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);
}
}
}
else {
// 初始化 bean
getBean(beanName);
}
}
}

// Trigger post-initialization callback for all applicable beans...
// 遍历beanNames, 触发所有 SmartInitializingSingleton 的后初始化回调
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
// 判断singletonInstance是否实现了SmartInitializingSingleton接口
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
// 是否存在 Java安全管理器
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
// 触发SmartInitializingSingleton实现类的afterSingletonsInstantiated方法
smartSingleton.afterSingletonsInstantiated();
}
}
}
}

11.1.1 AbstractBeanFactory#getMergedLocalBeanDefinition

定位: org.springframework.beans.factory.support.AbstractBeanFactory#getMergedLocalBeanDefinition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Bean定义公共的抽象类是AbstractBeanDefinition,普通的Bean在Spring加载Bean定义的时候,实例化出来的是GenericBeanDefinition,
* 而Spring上下文包括实例化所有Bean用的AbstractBeanDefinition是RootBeanDefinition,这时候就使用getMergedLocalBeanDefinition方法做了一次转化,
* 将非RootBeanDefinition转换为RootBeanDefinition以供后续操作。
*/
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
// 检查beanName对应的mergedBeanDefinitions是否存在于缓存中,此缓存是在beanFactoryPostProcessor中添加的
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null && !mbd.stale) {
// mdb已获取到, 且mbd不需要重新合并定义
return mbd;
}
// 如果不存在与缓存中或者需要重新合并定义,则根据beanName和BeanDefinition,获取mergedBeanDefinitions
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}

11.1.2 AbstractBeanFactory#getMergedBeanDefinition

定位: org.springframework.beans.factory.support.AbstractBeanFactory#getMergedBeanDefinition

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
/**
* 如果给定的BeanDefinition是一个子BeanDefinition, 则需要合并父BeanDefinition,最后返回对于给定的bean的RootBeanDefinition
*/
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {

synchronized (this.mergedBeanDefinitions) {
// 用于存储bd的MergedBeanDefinition
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;

// Check with full lock now in order to enforce the same merged instance.
// 检查beanName对应的MergedBeanDefinition是否存在于缓存中
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
// mbd 为null 并且 mbd需要重新合并
if (mbd == null || mbd.stale) {
previous = mbd;
mbd = null;
// 如果bd的parentName为空,代表bd没有父定义,无需与父定义进行合并操作
// bean的ParentName
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
// 如果bd的类型为RootBeanDefinition,则bd的MergedBeanDefinition就是bd本身,则直接克隆一个副本
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
// 否则,将bd作为参数,构建一个RootBeanDefinition。
// 正常使用下,BeanDefinition在被加载后是GenericBeanDefinition或ScannedGenericBeanDefinition
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
// bd存在父定义,需要与父定义合并
BeanDefinition pbd;
try {
// 获取父bean的名称,并进行转换
String parentBeanName = transformedBeanName(bd.getParentName());
// 如果当前beanName和父beanName不相同,那么递归调用合并方法
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
// 如果父定义的beanName与bd的beanName相同,则拿到父BeanFactory,
// 只有在存在父BeanFactory的情况下,才允许父定义beanName与自己相同,否则就是将自己设置为父定义
BeanFactory parent = getParentBeanFactory();
// 如果父BeanFactory是ConfigurableBeanFactory,则通过父BeanFactory获取父定义的MergedBeanDefinition
if (parent instanceof ConfigurableBeanFactory) {
// 从父BeanFactory获取BeanDefinition
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
else {
// 如果父BeanFactory不是ConfigurableBeanFactory,则抛异常
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
// 根据父BeanFactory获取的BeanDefinition创建新的BeanDefinition
mbd = new RootBeanDefinition(pbd);
// 将原始的部分属性拷贝到mbd
mbd.overrideFrom(bd);
}

// Set default singleton scope, if not configured before.
// 如果没有配置scope,则设置为默认的单例scope
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}

// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
// 一个bean包含非单例bean, 则他不是一个单例bean
// 我们在此时进行修改scope,因为这可能是外部bean的父子合并的结果,在这种情况下,原始内部beanDefinition将不会继承合并的外部bean的单例状态
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}

// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
// 将beanName与mbd放到mergedBeanDefinitions缓存,以便之后可以直接使用
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
if (previous != null) {
// 拷贝相关的MergedBeanDefinition字段
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
}
return mbd;
}
}

11.1.3 AbstractBeanFactory#doGetBean

定位: org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean

  • 根据传入的 beanName 转换成 Spring 中的 beanName
  • 查询缓存中的 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
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

// 传入的 name 可能是 beanName, alias, &beanName (FactoryBean)
// 将 name 转换成 beanName
final String beanName = transformedBeanName(name);
Object bean;

// Eagerly check singleton cache for manually registered singletons.
// 提前检查单例缓存中是否有手动注册的单例对象,跟循环依赖有关联
// 从缓存中获取已实例化的单例对象
Object sharedInstance = getSingleton(beanName);
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 + "'");
}
}
// 返回对象的实例
// 当你实现了FactoryBean接口的对象,需要获取具体的对象的时候就需要此方法来进行获取了
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}

else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 当对象都是单例的时候会尝试解决循环依赖的问题,但是原型模式下如果存在循环依赖的情况,那么直接抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}

// Check if bean definition exists in this factory.
// 检查该工厂中是否存在bean定义
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
// 父级创建对象 bean 实例
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}

// 如果不是做类型检查,那么表示要创建bean,此处在集合中做一个记录
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}

try {
// 此处做了BeanDefinition对象的转换,
// 当我们从xml文件中加载 BeanDefinition 对象的时候,封装的对象是 GenericBeanDefinition,
// 此处要做类型转换,如果是子类bean的话,会合并父类的相关属性
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);

// Guarantee initialization of beans that the current bean depends on.
// 确保当前bean依赖的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 + "'");
}
// 注册各个bean的依赖关系,方便进行销毁
registerDependentBean(dep, beanName);
try {
// 先实例化引用的 bean 实例
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}

// Create bean instance.
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 = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

else if (mbd.isPrototype()) {
// 原型模式的bean对象创建
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}

else {
// 指定的scope上实例化bean
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 {
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) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}

// Check if required type matches the type of the actual bean instance.
// 检查所需的类型是否与实际bean实例的类型匹配。
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
// 获取类型转换器,并且进行类型转换
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
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());
}
}
return (T) bean;
}
11.1.3.1 DefaultSingletonBeanRegistry#getSingleton(String, boolean)

定位: org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(String, boolean)

从缓存中获取单例对象

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
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从单例对象缓存(一级缓存)中获取beanName对应的单例对象
Object singletonObject = this.singletonObjects.get(beanName);
// 如果单例对象缓存中没有,并且该beanName对应的单例bean正在创建中(下面的代码只有在存在循环引用才会调用)
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
// 从早期单例对象缓存(二级缓存)中获取单例对象(之所称成为早期单例对象,
// 是因为earlySingletonObjects里的对象的都是通过提前曝光的ObjectFactory创建出来的,
// 还未进行属性填充等操作)
singletonObject = this.earlySingletonObjects.get(beanName);
// 如果在早期单例对象缓存(二级缓存)中也没有,并且允许创建早期单例对象引用
if (singletonObject == null && allowEarlyReference) {
// 当某些方法需要提前初始化的时候则会调用addSingletonFactory方法,
// 将对应的ObjectFactory初始化策略存储在三级缓存
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 如果存在单例对象工厂,则通过工厂创建一个单例对象
singletonObject = singletonFactory.getObject();
// 记录在缓存中,二级缓存和三级缓存的对象不能同时存在
this.earlySingletonObjects.put(beanName, singletonObject);
// 从三级缓存中移除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
11.1.3.2 DefaultSingletonBeanRegistry#getObjectForBeanInstance

定位: org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getObjectForBeanInstance

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
/**
* 获取给定bean实例的对象,即bean
* 实例本身或其创建的对象(对于FactoryBean)。
*/
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {

// Don't let calling code try to dereference the factory if the bean isn't a factory.
// 通过beanName判断是否有factoryBean的前缀(即 name包含&)
if (BeanFactoryUtils.isFactoryDereference(name)) { //
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
// beanInstance 没有实现 FactoryBean 接口
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}

// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
// 当我们有了bean的实例之后,这个实例可能是正常的bean,也可能是FactoryBean,
// 如果是FactoryBean那么就直接创建实例,
// 但是如果用户想要直接获取工厂实例而不是工厂的getObject方法对应的实例,那么传入的参数应该加&前缀
if (!(beanInstance instanceof FactoryBean)) {
// beanInstance 没有实现 FactoryBean 接口
return beanInstance;
}

// 创建FactoryBean中的bean
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
// 尝试从缓存中加载bean
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
// 将beanInstance转换为FactoryBean类型
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
// 将存储xml配置文件的 GenericBeanDefinition 转换为RootBeanDefinition,
// 如果指定BeanName是子Bean的话,同时会合并父类的相关属性
mbd = getMergedLocalBeanDefinition(beanName);
}
// 判断当前bean是否是用户定义的,而不是应用程序本身定义的
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic); // factory::getObject
}
return object;
}
11.1.3.2.1 FactoryBeanRegistrySupport#getObjectFromFactoryBean

定位: org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getObjectForBeanInstance

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
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
// 需要处理
if (shouldPostProcess) {
// 单例对象直接返回
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
beforeSingletonCreation(beanName);
try {
// 进行后置处理器处理
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
// 如果包含了FactoryBean,就将创建的对象缓存
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
else {
// FactoryBean是原型的话
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
// 调用ObjectFactory的后置处理器
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
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
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
throws BeanCreationException {

Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 直接调用getObject方法,返回具体的对象
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}

// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
if (object == null) {
// 如果是正在创建的FactoryBean,还没能获得bean,就报异常
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
object = new NullBean();
}
return object;
}
11.1.3.3 DefaultSingletonBeanRegistry#registerDependentBean

定位: org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#registerDependentBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public void registerDependentBean(String beanName, String dependentBeanName) {
// 获取name的最终别名或者是全类名
String canonicalName = canonicalName(beanName);

// 使用存储bean名称到该bean名称要依赖的bean名称的Map作为锁,保证线程安全
synchronized (this.dependentBeanMap) {
// 获取canonicalName对应的用于存储依赖Bean名的Set集合,如果没有就创建一个LinkeHashSet,
// 并与canonicalName绑定到dependentBeans中
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
// 如果dependentBeans已经添加过来了dependentBeanName,就结束该方法,不执行后面操作。
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}

// 使用Bean依赖关系Map作为锁,保证线程安全
synchronized (this.dependenciesForBeanMap) {
// 添加dependentBeanName依赖于canonicalName的映射关系到存储bean名到依赖于该bean名的bean名称的Map中
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
11.1.3.4 DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory<?>)

定位: org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#getSingleton(String, ObjectFactory<?>)

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
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);
// 如果对象不存在,才需要进行bean的实例化
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 + "'");
}
// 记录当前对象的加载状态,做个正在创建的标记
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 开始进行bean对象的创建
singletonObject = singletonFactory.getObject();
// 只要获取了就是新的单例对象
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 将单例对象放入一级缓存
this.singletonObjects.put(beanName, singletonObject);
// 将单例对象从三级缓存中移除
this.singletonFactories.remove(beanName);
// 将单例对象从二级缓存中移除
this.earlySingletonObjects.remove(beanName);
// 将单例对象 beanName 添加到 已注册的集合中
this.registeredSingletons.add(beanName);
}
}
0%