1 | public static void main(String[] args) { |
Version
:
- spring-context-6.0.0-SNAPSHOT.jar
- spring-beans-5.3.15.jar
- spring-aop-6.0.0-SNAPSHOT.jar
- spring-core-6.0.0-SNAPSHOT.jar
SpringApplication
SpringApplication.run(SampleTomcatApplication.class, args)
org.springframework.boot.SpringApplication#run(java.lang.Class<?>, java.lang.String…)
1
2
3
4
5
6
7
8
9
10
11/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified source using default settings.
* @param primarySource the primary source to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
//用于使用默认设置从指定源运行SpringApplication的Static helper
return run(new Class<?>[] { primarySource }, args);
}org.springframework.boot.SpringApplication#run(java.lang.Class<?>[], java.lang.String[])
1
2
3
4
5
6
7
8
9
10
11
12/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified sources using default settings and user supplied arguments.
* @param primarySources the primary sources to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
// 构建一个SpringApplication实例并调用run方法
// 用于使用默认设置和用户提供的参数从指定的源运SpringApplication的Static helper
return new SpringApplication(primarySources).run(args);
}
SpringApplication
org.springframework.boot.SpringApplication#SpringApplication(org.springframework.core.io.ResourceLoader, java.lang.Class<?>…)
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
private ResourceLoader resourceLoader;
private Set<Class<?>> primarySources;
private WebApplicationType webApplicationType;
private List<BootstrapRegistryInitializer> bootstrapRegistryInitializers;
private List<ApplicationContextInitializer<?>> initializers;
private List<ApplicationListener<?>> listeners;
private Class<?> mainApplicationClass;
/**
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources (see {@link SpringApplication class-level}
* documentation for details). The instance can be customized before calling
* {@link #run(String...)}.
* @param primarySources the primary bean sources
* @see #run(Class, String[])
* @see #SpringApplication(ResourceLoader, Class...)
* @see #setSources(Set)
*/
public SpringApplication(Class<?>... primarySources) {
//创建一个新的SpringApplication实例,设置 resourceLoader 以及暂存 primarySources。
//应用程序上下文将从指定的主要来源加载 bean。可以在调用run(String...)之前自定义实例
this(null, primarySources);
}
/**
*
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources (see {@link SpringApplication class-level}
* documentation for details). The instance can be customized before calling
* {@link #run(String...)}.
* @param resourceLoader the resource loader to use
* @param primarySources the primary bean sources
* @see #run(Class, String[])
* @see #setSources(Set)
*/
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//resourceLoader资源加载器,默认设置为 null,除非有特定的需求,否则一般不手动设置;
this.resourceLoader = resourceLoader;
//primarySources主要设置为包含 @SpringApplication 注解的类(正常情况下是启动类)
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 推断当前应用程序的类型,WebApplicationType定义了三个应用类型
//- NONE:应用程序不作为web应用启动,不启动内嵌的服务。
//- SERVLET:应用程序以基于servlet的web应用启动,需启动内嵌servlet web服务。
//- REACTIVE:应用程序以响应式web应用启动,需启动内嵌的响应式web服务。
//此处Tomcat返回的是 WebApplicationType.SERVLET
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//从META-INF/spring.factories中加载BootstrapRegistryInitializer的实例
//使用 ClassLoader 扫描所有 META-INF/spring.factories 文件,并用 Properties 加载并实例化BootstrapRegistryInitializer的实例,最后缓存在org.springframework.core.io.support.SpringFactoriesLoader#cache 中
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
// 从META-INF/spring.factories中加载ApplicationContextInitializer的实例
// 初始化Spring容器
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 从META-INF/spring.factories中加载ApplicationListener的监听器实例
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 推导出主类(包含 main 方法的主启动类)。这里利用了 Throwable 的 stackTrace 来查找的
this.mainApplicationClass = deduceMainApplicationClass();
}
/**
* Sets the {@link ApplicationContextInitializer} that will be applied to the Spring
* {@link ApplicationContext}.
* @param initializers the initializers to set
*/
public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList<>(initializers);
}
/**
* Sets the {@link ApplicationListener}s that will be applied to the SpringApplication
* and registered with the {@link ApplicationContext}.
* @param listeners the listeners to set
*/
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
this.listeners = new ArrayList<>(listeners);
}
private Class<?> deduceMainApplicationClass() {
return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(this::findMainClass)
.orElse(null);
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, null);
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, ArgumentResolver argumentResolver) {
return SpringFactoriesLoader.forDefaultResourceLocation(getClassLoader()).load(type, argumentResolver);
}
/**
* 将在 ApplicationContext 中使用的 ClassLoader(如果设置了resourceLoader ),或者上下文类加载器(如果不为 null),或者 Spring ClassUtils类的加载器
*
* Either the ClassLoader that will be used in the ApplicationContext (if
* {@link #setResourceLoader(ResourceLoader) resourceLoader} is set), or the context
* class loader (if not null), or the loader of the Spring {@link ClassUtils} class.
* @return a ClassLoader (never null)
*/
public ClassLoader getClassLoader() {
if (this.resourceLoader != null) {
return this.resourceLoader.getClassLoader();
}
return ClassUtils.getDefaultClassLoader();
}
forDefaultResourceLocation
org.springframework.core.io.support.SpringFactoriesLoader#forDefaultResourceLocation(java.lang.ClassLoader)
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/**
* org.springframework.core.io.support.SpringFactoriesLoader#FACTORIES_RESOURCE_LOCATION
*/
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
/**
* 创建一个SpringFactoriesLoader实例,该实例将使用给定的类加载器从"META-INF/spring.factories"加载和实例化工厂实现
*
* Create a {@link SpringFactoriesLoader} instance that will load and
* instantiate the factory implementations from
* {@value #FACTORIES_RESOURCE_LOCATION}, using the given class loader.
* @param classLoader the ClassLoader to use for loading resources; can be
* {@code null} to use the default
* @return a {@link SpringFactoriesLoader} instance
* @since 6.0
* @see #forDefaultResourceLocation()
*/
public static SpringFactoriesLoader forDefaultResourceLocation( { ClassLoader classLoader)
return forResourceLocation(FACTORIES_RESOURCE_LOCATION, classLoader);
}
/**
* 创建一个SpringFactoriesLoader实例,该实例将使用给定的类加载器从给定位置加载和实例化工厂实现
*
* Create a {@link SpringFactoriesLoader} instance that will load and
* instantiate the factory implementations from the given location, using
* the given class loader.
* @param resourceLocation the resource location to look for factories
* @param classLoader the ClassLoader to use for loading resources; can be
* {@code null} to use the default
* @return a {@link SpringFactoriesLoader} instance
* @since 6.0
* @see #forResourceLocation(String)
*/
public static SpringFactoriesLoader forResourceLocation(String resourceLocation, { ClassLoader classLoader)
Assert.hasText(resourceLocation, "'resourceLocation' must not be empty");
ClassLoader resourceClassLoader = (classLoader != null ? classLoader :
SpringFactoriesLoader.class.getClassLoader());
Map<String, SpringFactoriesLoader> loaders = SpringFactoriesLoader.cache.computeIfAbsent(
resourceClassLoader, key -> new ConcurrentReferenceHashMap<>());
return loaders.computeIfAbsent(resourceLocation, key ->
new SpringFactoriesLoader(classLoader, loadFactoriesResource(resourceClassLoader, resourceLocation)));
}
protected static Map<String, List<String>> loadFactoriesResource(ClassLoader classLoader, String resourceLocation) {
Map<String, List<String>> result = new LinkedHashMap<>();
try {
Enumeration<URL> urls = classLoader.getResources(resourceLocation);
while (urls.hasMoreElements()) {
UrlResource resource = new UrlResource(urls.nextElement());
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
properties.forEach((name, value) -> {
List<String> implementations = result.computeIfAbsent(((String) name).trim(), key -> new ArrayList<>());
Arrays.stream(StringUtils.commaDelimitedListToStringArray((String) value))
.map(String::trim).forEach(implementations::add);
});
}
result.replaceAll(SpringFactoriesLoader::toDistinctUnmodifiableList);
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" + resourceLocation + "]", ex);
}
return Collections.unmodifiableMap(result);
}
load
org.springframework.core.io.support.SpringFactoriesLoader#load(java.lang.Class
, org.springframework.core.io.support.SpringFactoriesLoader.ArgumentResolver) 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
77private final Map<String, List<String>> factories;
/**
* 使用配置的类加载器和给定的参数解析器从"META-INF/spring.factories"加载和实例化给定类型的工厂实现。
* 返回的工厂通过AnnotationAwareOrderComparator进行排序。
* 从 Spring Framework 5.3 开始,如果为给定的工厂类型发现重复的实现类名称,则只会实例化重复的实现类型的一个实例s
*
* Load and instantiate the factory implementations of the given type from
* {@value #FACTORIES_RESOURCE_LOCATION}, using the configured class loader
* and the given argument resolver.
* <p>The returned factories are sorted through {@link AnnotationAwareOrderComparator}.
* <p>As of Spring Framework 5.3, if duplicate implementation class names are
* discovered for a given factory type, only one instance of the duplicated
* implementation type will be instantiated.
* @param factoryType the interface or abstract class representing the factory
* @param argumentResolver strategy used to resolve constructor arguments by their type
* @throws IllegalArgumentException if any factory implementation class cannot
* be loaded or if an error occurs while instantiating any factory
* @since 6.0
*/
public <T> List<T> load(Class<T> factoryType, { ArgumentResolver argumentResolver)
return load(factoryType, argumentResolver, NO_FAILURE_HANDLER);
}
/**
* Load and instantiate the factory implementations of the given type from
* {@value #FACTORIES_RESOURCE_LOCATION}, using the configured class loader,
* the given argument resolver, and custom failure handling provided by the given
* failure handler.
* <p>The returned factories are sorted through {@link AnnotationAwareOrderComparator}.
* <p>As of Spring Framework 5.3, if duplicate implementation class names are
* discovered for a given factory type, only one instance of the duplicated
* implementation type will be instantiated.
* <p>For any factory implementation class that cannot be loaded or error that
* occurs while instantiating it, the given failure handler is called.
* @param factoryType the interface or abstract class representing the factory
* @param argumentResolver strategy used to resolve constructor arguments by their type
* @param failureHandler strategy used to handle factory instantiation failures
* @since 6.0
*/
public <T> List<T> load(Class<T> factoryType, { ArgumentResolver argumentResolver, FailureHandler failureHandler)
Assert.notNull(factoryType, "'factoryType' must not be null");
List<String> implementationNames = loadFactoryNames(factoryType);
logger.trace(LogMessage.format("Loaded [%s] names: %s", factoryType.getName(), implementationNames));
List<T> result = new ArrayList<>(implementationNames.size());
FailureHandler failureHandlerToUse = (failureHandler != null) ? failureHandler : THROWING_FAILURE_HANDLER;
for (String implementationName : implementationNames) {
T factory = instantiateFactory(implementationName, factoryType, argumentResolver, failureHandlerToUse);
if (factory != null) {
result.add(factory);
}
}
AnnotationAwareOrderComparator.sort(result);
return result;
}
private List<String> loadFactoryNames(Class<?> factoryType) {
return this.factories.getOrDefault(factoryType.getName(), Collections.emptyList());
}
protected <T> T instantiateFactory(String implementationName, Class<T> type,
{ ArgumentResolver argumentResolver, FailureHandler failureHandler)
try {
Class<?> factoryImplementationClass = ClassUtils.forName(implementationName, this.classLoader);
Assert.isTrue(type.isAssignableFrom(factoryImplementationClass),
() -> "Class [%s] is not assignable to factory type [%s]".formatted(implementationName, type.getName()));
FactoryInstantiator<T> factoryInstantiator = FactoryInstantiator.forClass(factoryImplementationClass);
return factoryInstantiator.instantiate(argumentResolver);
}
catch (Throwable ex) {
failureHandler.handleFailure(type, implementationName, ex);
return null;
}
}
SpringApplication(primarySources).run(args)
org.springframework.boot.SpringApplication#run(java.lang.String…)
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/**
* 运行 Spring 应用程序,创建并刷新一个新的ApplicationContext(应用上下文)
*
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
//可以观察SpringApplication并修改其行为的低级回调函数。当多个应用程序并行执行时,挂钩在每个线程的基础上进行管理,从而提供隔离
SpringApplicationHooks.hooks()
//在SpringApplication.run(String...)的开头调用。提供检查和自定义应用程序的机会
.preRun(this);
long startTime = System.nanoTime();
//初始化上下文
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
// 配置Headless属性
configureHeadlessProperty();
// 从META-INF/spring.factories中加载SpringApplicationRunListener的实例,并封装到SpringApplicationRunListeners对象当中(SpringBoot监听器,启动周期监听器)
SpringApplicationRunListeners listeners = getRunListeners(args);
// 监听器广播事件:开始启动中
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
// 将默认运行参数 封装进ApplicationArguments中
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 准备 Environment(用于读取配置)
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
// 读取配置中需要忽略的配置,将包含该配置的对象忽略
configureIgnoreBeanInfo(environment);
// 打印Banner
Banner printedBanner = printBanner(environment);
// 通过反射创建 应用上下文Instance。 这里初始化了三级缓存的Map和BeanDefinitionMap
// 若是Servlet应用,则返回AnnotationConfigSerlvetWebServerApplicationContext的实例。
// 实际返回的 是 ApplicationContext的子类AnnotationConfigServletWebServerApplicationContext的实例
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
// 准备 应用上下文(向上下文对象中设置一系列的属性值),此刻Spring容器中已经生成配置类
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
// 刷新Context,若执行刷新成功,则返回true
if (refreshContext(context)) {
// 在Context刷新后,默认是空方法
afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(),
timeTakenToStartup);
}
// 广播事件:已启动
listeners.started(context, timeTakenToStartup);
// 调用 Runner,包括CommandLineRunner和ApplicationRunner的实例
callRunners(context, applicationArguments);
}
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
if (context.isRunning()) {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
}
}
catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
SpringApplicationHooks.hooks().postRun(this, context);
return context;
}
createBootstrapContext
org.springframework.boot.SpringApplication#createBootstrapContext
1
2
3
4
5
6//创建默认的 DefaultBootstrapContext,并对初始化所收集到的所有 bootstrappers 执行 initialize 方法,将 context 作为该方法的参数
private DefaultBootstrapContext createBootstrapContext() {
DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext();
this.bootstrapRegistryInitializers.forEach((initializer) -> initializer.initialize(bootstrapContext));
return bootstrapContext;
}
configureHeadlessProperty
org.springframework.boot.SpringApplication#configureHeadlessProperty
1
2
3
4
5//设置 java.awt.headless,如果未进行过自定义设置(如:application.setHeadless(false)、System.setProperties("java.awt.headless", false)或者 JVM 参数:java -Djava.awt.headless=true),则默认设置为 true。如果项目为非 GUI 类型的,如 console 或者 server 类型,建议设置为 true,否则设置为 false;
private void configureHeadlessProperty() {
System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,
System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}
getRunListeners
org.springframework.boot.SpringApplication#getRunListeners
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/*
* 获取所有的 org.springframework.boot.SpringApplicationRunListener(从初始化过程中的 org.springframework.core.io.support.SpringFactoriesLoader#cache 中查找),并封装在 SpringApplicationRunListeners 中。该 Listener 中主要定义了 spring application 的生命周期:starting、environmentPrepared、contextPrepared、contextLoaded、started、running 以及 failed。该配置存在于 spring-boot-x.y.z.jar!/META-INF/spring.factories 中:
*
* # Run Listeners
* org.springframework.boot.SpringApplicationRunListener=\
* org.springframework.boot.context.event.EventPublishingRunListener
* 初始化 EventPublishingRunListener 过程中创建了应用初始化事件管理器,并将 SpringApplication
* 初始化过程中收集到的 listeners 添加进入
*/
private SpringApplicationRunListeners getRunListeners(String[] args) {
ArgumentResolver argumentResolver = ArgumentResolver.of(SpringApplication.class, this);
argumentResolver = argumentResolver.and(String[].class, args);
Collection<SpringApplicationRunListener> listeners = getSpringFactoriesInstances(
SpringApplicationRunListener.class, argumentResolver);
return new SpringApplicationRunListeners(logger, listeners, this.applicationStartup);
}org.springframework.boot.SpringApplicationRunListeners#starting
1
2
3
4
5
6
7
8
9// 紧接着利用上一步所找到的 run listeners,执行生命周期的第一个方法 starting
void starting(ConfigurableBootstrapContext bootstrapContext, Class<?> mainApplicationClass) {
doWithListeners("spring.boot.application.starting", (listener) -> listener.starting(bootstrapContext),
(step) -> {
if (mainApplicationClass != null) {
step.tag("mainApplicationClass", mainApplicationClass.getName());
}
});
}
prepareEnvironment
org.springframework.boot.SpringApplication#prepareEnvironment
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/*
* 根据初始化过程中所推导的 WEB 应用类型创建不同类型的可配置 Environment(ConfigurableEnvironment);
* 创建默认的转换器,并设置到可配置的 Environment 中;
* 从自定义阶段配置的 defaultProperties 以及命令行参数中获得配置(两个 PropertySource:defaultProperties(低优先级) 和 commandLineArgs(高优先级)),并添加到可配置的 Environment 中;
* 将当前的配置用 ConfigurationPropertySource 包装,以便在未来使用 PropertySourcesPropertyResolver 解析配置名;
* 通知所有监听器,环境变量已准备就绪;
* 将名为 defaultProperties 的 PropertySource 移动到最后;
* 根据自定义阶段所配置的 additionalProfiles 追加可配置的 Environment 的 activeProfiles;
* 将 SpringApplication 的配置设置到 Environment 中,配置前缀为:spring.main.,如 spring.main.banner-mode=console;
* 如果未设置自定义环境,则会将此前创建的 Environment 复制(浅拷贝)一份,类型为 StandardEnvironment;
* 重复第 3 步。
*/
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach(environment);
listeners.environmentPrepared(bootstrapContext, environment);
DefaultPropertiesPropertySource.moveToEnd(environment);
Assert.state(!environment.containsProperty("spring.main.environment-prefix"),
"Environment prefix cannot be set via properties.");
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
EnvironmentConverter environmentConverter = new EnvironmentConverter(getClassLoader());
environment = environmentConverter.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
configureIgnoreBeanInfo
org.springframework.boot.SpringApplication#configureIgnoreBeanInfo
1
2
3
4
5
6
7private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
if (System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) {
Boolean ignore = environment.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME,
Boolean.class, Boolean.TRUE);
System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, ignore.toString());
}
}
createApplicationContext
org.springframework.boot.SpringApplication#createApplicationContext
1
2
3
4
5
6
7
8
9
10
11
12/**
* 根据 WEB 应用类型创建对应的 ConfigurableApplicationContext,这里仅仅是创建该实例,还并未真正准备
*
* Strategy method used to create the {@link ApplicationContext}. By default this
* method will respect any explicitly set application context class or factory before
* falling back to a suitable default.
* @return the application context (not yet refreshed)
* @see #setApplicationContextFactory(ApplicationContextFactory)
*/
protected ConfigurableApplicationContext createApplicationContext() {
return this.applicationContextFactory.create(this.webApplicationType);
}org.springframework.context.ConfigurableApplicationContext#setApplicationStartup
1
2
3
4
5
6
7
8/**
* Set the {@link ApplicationStartup} for this application context.
* <p>This allows the application context to record metrics
* during startup.
* @param applicationStartup the new context event factory
* @since 5.3
*/
void setApplicationStartup(ApplicationStartup applicationStartup);org.springframework.context.support.AbstractApplicationContext#setApplicationStartup
1
2
3
4
5
6// 将 applicationStartup 设置到 ApplicationContext 中,主要是为了统计接下来的步骤所消耗的时间
public void setApplicationStartup(ApplicationStartup applicationStartup) {
Assert.notNull(applicationStartup, "applicationStartup should not be null");
this.applicationStartup = applicationStartup;
}
prepareContext
org.springframework.boot.SpringApplication#prepareContext
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51// 准备 BootstrapContext 和 ApplicationContext
// 把所有需要管理的 Bean 统计出来
private void prepareContext(DefaultBootstrapContext bootstrapContext, ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
// 设置环境
context.setEnvironment(environment);
// 注册自定义 BeanNameGenerator 到 ApplicationContext 的 BeanFactory 中;
postProcessApplicationContext(context);
addAotGeneratedInitializerIfNecessary(this.initializers);
//
applyInitializers(context);
listeners.contextPrepared(context);
bootstrapContext.close(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
// 一般是DefaultListableBeanFactory
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof AbstractAutowireCapableBeanFactory autowireCapableBeanFactory) {
autowireCapableBeanFactory.setAllowCircularReferences(this.allowCircularReferences);
if (beanFactory instanceof DefaultListableBeanFactory listableBeanFactory) {
// 允许Bean信息被覆盖
listableBeanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
}
//是否懒加载
if (this.lazyInitialization) {
//
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
context.addBeanFactoryPostProcessor(new PropertySourceOrderingBeanFactoryPostProcessor(context));
if (!AotDetector.useGeneratedArtifacts()) {
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// load () 方法真正的作用是去调用 BeanDefinitionLoader 类的 load () 方法
// load ((Class<?>) source) 中会通过调用 isComponent () 方法来判断资源是否为 Spring 容器管理的组件。
//isComponent () 方法通过资源是否包含 @Component 注解(@Controller、@Service、@Repository 等都包含在内)来区分是否为 Spring 容器管理的组件。
//而 load ((Package) source) 方法则是用来加载 @ComponentScan 注解定义的包路径
load(context, sources.toArray(new Object[0]));
}
//
listeners.contextLoaded(context);
}
refreshContext
org.springframework.boot.SpringApplication#refreshContext
1
2
3
4
5
6
7
8
9
10private boolean refreshContext(ConfigurableApplicationContext context) {
if (!SpringApplicationHooks.hooks().preRefresh(this, context)) {
return false;
}
if (this.registerShutdownHook) {
shutdownHook.registerApplicationContext(context);
}
refresh(context);
return true;
}
afterRefresh
org.springframework.boot.SpringApplication#afterRefresh
1
2
3
4
5
6
7/**
* Called after the context has been refreshed.
* @param context the application context
* @param args the application arguments
*/
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}
callRunners
org.springframework.boot.SpringApplication#callRunners
1
2
3
4
5
6
7
8
9
10
11
12
13
14private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<>(runners)) {
if (runner instanceof ApplicationRunner applicationRunner) {
callRunner(applicationRunner, args);
}
if (runner instanceof CommandLineRunner commandLineRunner) {
callRunner(commandLineRunner, args);
}
}
}
postRun
org.springframework.boot.SpringApplicationHooks.Hooks#postRun
1
2
3
4
5
6
public void postRun(SpringApplication application, ConfigurableApplicationContext context) {
for (Hook delegate : this.delegates) {
delegate.postRun(application, context);
}
}
Refresh()
org.springframework.context.ConfigurableApplicationContext#refresh
1
2
3
4
5
6
7
8
9
10
11
12/**
* Load or refresh the persistent representation of the configuration, which
* might be from Java-based configuration, an XML file, a properties file, a
* relational database schema, or some other format.
* <p>As this is a startup method, it should destroy already created singletons
* if it fails, to avoid dangling resources. In other words, after invocation
* of this method, either all or no singletons at all should be instantiated.
* @throws BeansException if the bean factory could not be initialized
* @throws IllegalStateException if already initialized and multiple refresh
* attempts are not supported
*/
void refresh() throws BeansException, IllegalStateException;org.springframework.context.support.AbstractApplicationContext#refresh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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/**
* ConfigurableApplicationContext#refresh 加载或者刷新持久化配置
* 刷新应用上下文
* Load or refresh the persistent representation of the configuration, which might be from Java-based configuration, an XML file, a properties file, a relational database schema, or some other format.
* As this is a startup method, it should destroy already created singletons if it fails, to avoid dangling resources. In other words, after invocation of this method, either all or no singletons at all should be instantiated.
* @throws BeansException
* @throws IllegalStateException
*/
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 准备刷新阶段 Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 创建容器对象,DefaultListableBeanFactory
// BeanFactory创建阶段 加载XML配置文件的属性值到当前工厂中,最重要的就是BeanDefinition
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// BeanFactory准备阶段,对各种属性填充
// 注册属性编辑器 BeanPostProcessor等
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// BeanFactory后置处理阶段
// 子类覆盖方法做额外的处理,此处自己一般不做任何拓展工作,都是可以看web中代码,有具体实现
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// BeanFactory后置处理阶段
// 按次序回调BeanFactoryPostProcessor接口
// 重点:会回调ConfigurationClassPostProcessor注入@Configuration,@ComponmentScan等配置的类
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// BeanFactory注册BeanPostProcessor阶段
// 按顺序注册BeanPostProcessor,这里仅注册,真正调用是getBean方法
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 初始化内建Bean
// 为上下文初始化message源,即不同语言的消息体,国际化处理
initMessageSource();
// Initialize event multicaster for this context.
// 初始化内建Bean
// 初始化事件监听多路广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// Spring应用上下文刷新阶段, 留给子类初始化其他Bean
onRefresh();
// Check for listener beans and register them.
// Spring事件监听器注册阶段:在所有注册的Bean中查找Listener Bean,注册到消息广播中
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// BeanFactory初始化完成阶段: 初始化剩下的单实例(非懒加载的)
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// Spring应用上下文完成刷新阶段: 通知生命周期处理器LifecycleProcessor刷新过程,同时发出ContextRefreshEvent事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
// 为防止Bean资源占有,在异常处理中,销毁已经在前面过程中生成的单例Bean
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
// 清空产生的缓存数据
resetCommonCaches();
contextRefresh.end();
}
}
}
prepareRefresh()
org.springframework.context.support.AbstractApplicationContext#prepareRefresh
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/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
//初始化属性源,扩展用(该方法默认是空的,是提供给子类来实现的,
//假设我们有些工作需要在初始化bean以前就要加载设置等,可以通过重写这个方法来完成)
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 校验必要属性
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
// 创建存储早期applicationListeners容器
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 创建存储早期applicationEvents容器,存储早期Spring Application事件,用于后面applicationEventMulticaster发布事件用
this.earlyApplicationEvents = new LinkedHashSet<>();
}
obtainFreshBeanFactory()
org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15/**
* 重新创建一个bean工厂
*
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新BeanFactory,创建一个 DefaultListableBeanFactory类型的 BeanFactory
//赋值给 beanFactory 属性,对创建的这个 beanFactory 设置一个序列号
refreshBeanFactory();
//将上一步设置好序列号的的beanFactory返回
return getBeanFactory();
}org.springframework.context.support.GenericApplicationContext#refreshBeanFactory
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/**
* 刷新BeanFactory
* Debug break point进入这一个类,可能是纯Annotation导致
*
* Do nothing: We hold a single internal BeanFactory and rely on callers
* to register beans through our public methods (or the BeanFactory's).
* @see #registerBeanDefinition
*/
protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
//创建一个DefaultListableBeanFactory并设置Id
this.beanFactory.setSerializationId(getId());
}
/**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/
protected final void refreshBeanFactory() throws BeansException {
// 如果已存在BeanFactory,销毁Bean,并且关闭BeanFactory
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
// 创建DefaultListableBeanFactory(一般情况下都是DefaultListableBeanFactory)
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 设置BeanFactory id
beanFactory.setSerializationId(getId());
// 设置BeanFactory是否允许BeanDefinition重复定义,是否允许循环引用
customizeBeanFactory(beanFactory);
// 加载BeanDefinition
loadBeanDefinitions(beanFactory);
// 关联新建的BeanFactory到Spring应用上下文
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}org.springframework.context.support.GenericApplicationContext#getBeanFactory
1
2
3
4
5
6
7
8
9
10/**
* 返回刚刚创建的带Id的DefaultListableBeanFactory
*
* Return the single internal BeanFactory held by this context
* (as ConfigurableListableBeanFactory).
*/
public final ConfigurableListableBeanFactory getBeanFactory() {
return this.beanFactory;
}
prepareBeanFactory(beanFactory)
org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory
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/**
* BeanFactory的预准备工作
*
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 设置ClassLoader
beanFactory.setBeanClassLoader(getClassLoader());
if (!shouldIgnoreSpel) {
//设置Bean表达式语言解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
}
// 添加 PropertyEditorRegistrar 的实现 ResourceEditorRegistrar
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 注册BeanPostProcessor(ApplicationContextAwareProcessor), 用来处理Aware回调接口
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
//设置忽略Aware回调接口作为自动装配接口,就是设置这些接口的实现类不能通过这些接口实现自动注入
beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 注册可解析的自动装配ResolvableDependency对象-BeanFactory,ResourceLoader,ApplicationEventPublisher,ApplicationContext
// 假设想要使用 @Autowired 注解将Spring提供的 BeanFactory 装配到自己,创建的某个类的属性上,就要在此处设置
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 注册BeanPostProcessor(ApplicationListenerDetector(this))后置处理器, 用来处理ApplicationListener接口
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 添加编译时AspectJ支持
if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
// 注册BeanPostProcessor (LoadTimeWeaverAwareProcessor), 用来处理aop
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
// 给BeanFactory中注册单例对象组件 (Environment,Java System Properties以及OS环境变量)
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
//注册了一个 Environment,该对象中存了一下我们默认的属性
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
//向beanFactory中注册了系统属性属性(一个Map集合)
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
//向beanFactory中注册环境变量等相关信息(一个Map集合)
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
postProcessBeanFactory(beanFactory)
org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory
1
2
3
4
5
6
7
8
9
10
11
12/**
* BeanFactory 准备工作完成后进行的后置处理工作
* 子类通过重写此方法 / 实现BeanFactoryPostProcessor接口 在BeanFactory创建并预准备完成后做进一步设置
*
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
BeanFactory的创建与预准备工作完成分割线
invokeBeanFactoryPostProcessors(beanFactory)
org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors
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/**
* 执行实现了 BeanFactoryPostProcessors 接口的beanFactory后置处理器中方法,也就是beanFactory初始化完成后要执行的方法
* 注意 BeanFactory 后置处理器 BeanFactoryPostProcessor 与 BeanDefinitionRegistryPostProcessor的不同
* 这个方法必须在所有的singleton初始化之前调用
*
* 实例化并调用所有已注册的 BeanFactoryPostProcessor
* 两个接口:
* BeanDefinitionRegistryPostProcessor
* BeanFactoryPostProcessor
*
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//在此获取所有BeanFactoryPostProcessor遍历判断 对不同的BeanFactoryPostProcessor进行排序,因为先后执行的顺序不同
//PriorityOrdered>BeanDefinitionRegistryPostProcessor>BeanFactoryPostProcessor
//然后执行后置处理器中定义的初始化 beanFactory 后要执行的方法
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
registerBeanPostProcessors(beanFactory)
org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors
registerBeanPostProcessors(beanFactory);
不同类型的BeanPostProcessor在Bean创建前后的执行时机不同DestructionAwareBeanPostProcessor.
InstantiationAwareBeanPostProcessor.
SmartInstantiationAwareBeanPostProcessor,
MergedBeanDefinitionPostProcessor(InternalPostProcessors).
1
2
3
4
5
6
7
8
9
10
11
12/**
* 注册BeanPostProcessor(Bean后置处理器)
* 拦截Bean创建过程
* 这个方法需要在所有的application bean初始化之前调用。把这个注册的任务委托给了PostProcessorRegistrationDelegate来完成
*
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, org.springframework.context.support.AbstractApplicationContext)
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
100public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// WARNING: Although it may appear that the body of this method can be easily
// refactored to avoid the use of multiple loops and multiple lists, the use
// of multiple lists and multiple passes over the names of processors is
// intentional. We must ensure that we honor the contracts for PriorityOrdered
// and Ordered processors. Specifically, we must NOT cause processors to be
// instantiated (via getBean() invocations) or registered in the ApplicationContext
// in the wrong order.
//
// Before submitting a pull request (PR) to change this method, please review the
// list of all declined PRs involving changes to PostProcessorRegistrationDelegate
// to ensure that your proposal does not result in a breaking change:
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// 根据类型获取所有的BeanPostProcessor名称
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
// 添加了一个后置处理器,通过添加的这个后置处理器检查
// 前获取的这些后置处理器 BeanPostProcessorChecker 是一个内部类,继承了BeanPostProcessor接口
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// 创建两个集合用来存放不同的BeanPostProcessor,通过这两个集合对不同的BeanPostProcessor 进行优先级处理
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
//遍历获取 BeanPostProcessor, 判断不同的 BeanPostProcessor 放入不同的集合中
//实现了 PriorityOrdered 的放入priorityOrderedPostProcessors集合中
//实现了PriorityOrdered 并且是MergedBeanDefinitionPostProcessor类型的放入internalPostProcessors
//实现了 Ordered 的放入 orderedPostProcessorNames 集合中
//否则放入 nonOrderedPostProcessorNames 集合中
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 对 priorityOrderedPostProcessors 中的进行排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 优先注册 implement PriorityOrdered接口的
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 再注册 implement Ordered接口的
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
// MergedBeanDefinitionPostProcessor类型的放入internalPostProcessors
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
// 对orderedPostProcessors集合中的后置处理器排序
sortPostProcessors(orderedPostProcessors, beanFactory);
// 注册
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
// 在此注册不实现任何优先级接口的
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
//MergedBeanDefinitionPostProcessor类型的放入internalPostProcessors
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// 最终注册MergedBeanDefinitionPostProcessor(internalPostProcessors)
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 通过判断是否为ApplicationListener后,如果是, 通过先删后增方式增加最后一个ApplicationListenerDetector
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
initMessageSource()
org.springframework.context.support.AbstractApplicationContext#initMessageSource
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/**
* 初始化MessageSource 国际化功能,消息绑定,消息解析
* 作用: 获取国际化配置中某个Key的Value;能按照区域信息获取
*
* Initialize the MessageSource.
* Use parent's if none defined in this context.
*/
protected void initMessageSource() {
// 获取ConfigurableListableBeanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 判断容器中是否存在ID为MESSAGE_SOURCE_BEAN_NAME的组件
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
// 有 则赋值给this.messageSource。
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms) {
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
// 没有则创建一个DelegatingMessageSource进行赋值
DelegatingMessageSource dms = new DelegatingMessageSource();
// 将这个组件注册到容器中(以后获取国际化配置文件的相关信息,可以通过@Autowired在Spring
// 容器中直接获取装配到自己的类的属性上,然后调用MessageSource的方法)
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
initApplicationEventMulticaster()
org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster
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/**
* 初始化事件派发器
* 如果上下文中没有定义,则使用SimpleApplicationEventMulticaster
*
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
// 获取ConfigurableListableBeanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 如果包含applicationEventMulticaster
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
//则对this.applicationEventMulticaster赋值
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 不包含,则创建一个SimpleApplicationEventMulticaster(beanFactory)并赋值
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
//注册成Singleton
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
onRefresh()
org.springframework.context.support.AbstractApplicationContext#onRefresh
1
2
3
4
5
6
7
8
9
10
11
12
13/**
* 给子类的模板方法
* 子类重写方法,在容器刷新时可以自定义逻辑
*
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* <p>This implementation is empty.
* @throws BeansException in case of errors
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}org.springframework.web.context.support.GenericWebApplicationContext#onRefresh
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh
1
2
3
4
5
6
7
8
9
10
11
protected void onRefresh() {
super.onRefresh();
try {
//创建及启动内嵌Tomcat
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
registerListeners()
org.springframework.context.support.AbstractApplicationContext#registerListeners
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/**
* 将所有实现ApplicationListener的监听器类注册
* 注册完以后,还会将其前期的事件发布给相匹配的监听器
*
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 获取所有的ApplicationListener
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
// 遍历
for (String listenerBeanName : listenerBeanNames) {
// 新增进入ApplicationEventMulticaster
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
// 如果有早期事件,则进行派发
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
finishBeanFactoryInitialization(beanFactory)
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
41
42
43
44/**
* Spring应用上下文的BeanFactory的初始化完成阶段
* 初始化剩下的所有的单实例Bean
*
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
//如果BeanFactory有ConversionService对象,关联到BeanFactory
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
//添加StringValueResolver对象
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.
// BeanFactory临时ClassLoader置为null
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// BeanFactory冻结配置
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有不是懒加载的Singleton Beans
beanFactory.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
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/**
* Ensure that all non-lazy-init singletons are instantiated, also considering
* {@link org.springframework.beans.factory.FactoryBean FactoryBeans}.
* Typically invoked at the end of factory setup, if desired.
* @throws BeansException if one of the singleton beans could not be created.
* Note: This may have left the factory with some beans already initialized!
* Call {@link #destroySingletons()} for full cleanup in this case.
* @see #destroySingletons()
*/
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方法,而init方法反过来注册新的bean定义。
// 盛放所有的beanName,所有的需要实例化的beanName都在这里,包括Spring断断续续添加的, Aspectj的, 程序员通过注解标识的
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 触发所有非延迟加载单例beans的初始化,主要步骤为调用getBean
for (String beanName : beanNames) {
// 合并父类BeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 非抽象,单例,非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
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) {
getBean(beanName);
}
}
}
else {
// 如果没有添加FactoryBean类型的对象, 一般都会进入这个getBean
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
.tag("beanName", beanName);
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
smartInitialize.end();
}
}
}
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}
doGetBean
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)
->
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
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/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
protected <T> T doGetBean(
String name, boolean typeCheckOnly) Class<T> requiredType, Object[] args,
throws BeansException {
String beanName = transformedBeanName(name);
Object beanInstance;
// Eagerly check singleton cache for manually registered singletons.
// 及早的检查一下有没有已经注册了的单例对象, 之前已创建的Singleton Bean都会先保存
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 + "'");
}
}
// 如果存在的话,将其取出赋值给bean,后续直接返回这个bean
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 来到这里就说明要获取的bean还没有实例化过
// 于是检验一下,如果是原形,直接抛异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 如果缓存中不存在,则开始创建
// 三级缓存?
// 检查是否存在默认的父工厂
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.
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);
}
}
if (!typeCheckOnly) {
// // 将当前的beanName存放到AlreadeyCreated这个set集中, 标记当前Bean已被创建
markBeanAsCreated(beanName);
}
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
.tag("beanName", name);
try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
// 获取Bean的定义信息
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 获取当前Bean依赖的其他Bean, 确保当前bean所依赖的bean都已经初始化好了
String[] dependsOn = mbd.getDependsOn();
// 依赖Bean不为空时,先将依赖的Bean进行创建
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
// 如果是Singleton,在此启动Singleton Bean的 实例化 流程
if (mbd.isSingleton()) {
// 调用DefaultSingletonBeanRegistry.getSingleton获取单例对象实例
// 这个方法的参数时,beanName 和 ObjectFactory, 这里new一个匿名实现类
sharedInstance = getSingleton(beanName, () -> {
try {
// 调用AbstractAutowireCapableBeanFactory.createBean, 真正的完成bean的创建
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的实例对象
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
}
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);
}
});
beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end();
}
}
return adaptBeanInstance(name, beanInstance, requiredType);
}
createBean
org.springframework.beans.factory.support.AbstractBeanFactory#createBean
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/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
protected Object createBean(String beanName, RootBeanDefinition mbd, 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.
// 将 bean 类名称解析为 Class 引用
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// 确保此时实际解析了 bean 类
// 并克隆 bean 定义以防动态解析的 Class 无法存储在共享的合并 bean 定义中
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
// 准备覆盖overrides方法,检查查找方法是否存在并确定它们的重载状态
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.
// Aop功能: 让InstantiationAwareBeanPostProcessor在 实例化前 先返回代理对象,如果能返回则直接返回一个代理对象代替这个bean
// 先执行InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()
// 若有返回,执行InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
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 {
// InstantiationAwareBeanPostProcessor没有返回时,调用这里
// 之前都是做一些检查工作,此处调用doCreateBean 才开始创建bean实例
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}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
24
25
26
27
28
29/**
* Apply before-instantiation post-processors, resolving whether there is a
* before-instantiation shortcut for the specified bean.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return the shortcut-determined bean instance, or {@code null} if none
*/
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 如果此时还没有被解析
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
// 如果是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;
}org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation
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
60public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
Object cacheKey = this.getCacheKey(beanClass, beanName);
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if (this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
if (StringUtils.hasLength(beanName)) {
this.targetSourcedBeans.add(beanName);
}
Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
} else {
return null;
}
}
public Object postProcessAfterInitialization( { Object bean, String beanName)
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
return bean;
} else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
} else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {
Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
} else {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
} else {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
}
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/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
* <p>Differentiates between default bean instantiation, use of a
* factory method, and autowiring a constructor.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
* @see #instantiateBean
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
*/
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args)
throws BeanCreationException {
// Instantiate the bean.
// 开始实例化
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// factoryBeanInstanceCache : 未完成的 FactoryBean 实例的缓存, Map<beanName, BeanWrapper>
// 将这个bean从未完成的缓存中移除
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 实例化 Bean Instance, 根据不同的实例化策略实例化bean,如工厂方法、构造函数自动装配或简单实例化
// 同时将 BeanDefinition 转化为 BeanWrapper
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
// 允许后处理器修改合并的 bean 定义。
synchronized (mbd.postProcessingLock) {
// 同步代码块,通知只能有一个线程对bean进行后置处理
if (!mbd.postProcessed) {
try {
// 调用MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition()
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.
// 优先解决循环依赖
// 提前暴力ObjectFactory,这里可能会出现 BeanFactoryAware 等生命周期接口触发的情况,但是相比循环依赖,还是要先处理循环依赖
// 必须满足3个条件 单例模式、允许提前暴露、单例对象正常被创建中
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");
}
// 提前暴露给 SingletonFactory
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 初始化前-赋值: Bean Instance - 给Bean 填充属性,使用 BeanDefinition中的属性值填充BeanWrapper 中的 Bean 实例
populateBean(beanName, mbd, instanceWrapper);
// Singleton Bean 执行初始化, 这个方法内处理Aware回调,调用init方法,执行初始化前后的bean处理器
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
// 提前暴露BeanFactory
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
// 表示已经缓存了这个对象了,直接通过通过name获取bean
if (earlySingletonReference != null) {
if (exposedObject == bean) {
// 直接使用缓存重点bean
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 如果不允许循环依赖,但是出现了所依赖的beanMap缓存中又出现了这个bean,那么此时就是出现了循环依赖
// 通过beanName拿到这个bean的所有依赖对象
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 删除给定 bean 名称的单例实例(如果有),但前提是它没有用于类型检查以外的其他目的
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
// 删除失败了,添加到循环依赖的数组中
actualDependentBeans.add(dependentBean);
}
}
// 循环依赖的bean没有没完全删除,抛出异常
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
// 将给定的 bean 添加到该工厂的一次性 bean 列表中,仅适用于单例
// spring 关闭时,如果满足下面的条件之一,就调用destroy()
// 实现Disposable接口、自定义destroy()方法、实现AutoCloseable
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}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
79
80
81
82
83/**
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a BeanWrapper for the new instance
* @see #obtainFromSupplier
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
* @see #instantiateBean
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, { Object[] args)
// Make sure bean class is actually resolved at this point.
// createBean方法已经解析过了,为了确保此时实际解析了,再次解析这个bean 类
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 解析失败
// 没有public修饰
// 不允许访问非公共构造函数和方法
// 出现以上三种情况,无法在外部实例化,抛出异常
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中的supplier实例化这个bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
// 利用Bean工厂创建Bean
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
// 通过构造方法创建这个bean
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
// constructorArgumentLock 构造参数锁,针对构造起作用
synchronized (mbd.constructorArgumentLock) {
// resolvedConstructorOrFactoryMethod : 缓存解析的构造函数或工厂方法
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
// constructorArgumentsResolved 构造函数参数解析状态
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
// 自动设配参数 使用有参构造实例化bean
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 无参构造实例化bean
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// 自动装配的候选构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
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.
// 没有特殊处理:只需使用无参数构造函数
return instantiateBean(beanName, mbd);
}
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
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/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param bw the BeanWrapper with bean instance
*/
// for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, { BeanWrapper bw)
if (bw == null) {
// 如果beanWrapper是null,同时没有属性,也就无法填充,直接返回一个空实例
// 如果有属性需要填充,又不能为null填充,抛出异常
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
// 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.
// 赋值前: 查看是否存在InstantiationAwareBeanPostProcessor,若有则执行postProcessAfterInstantiation
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 此时,可以在在设置属性之前修改 bean 的状态
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
// 在通过构造函数或工厂方法实例化 bean 之后,但在 Spring 属性填充(来自显式属性或自动装配)发生之前执行操作。
// 在 Spring 的自动装配开始之前,给定 bean 实例上执行自定义字段注入的理想回调,
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 自动注入@Autowire注解的属性
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
// 根据名称自动装配属性值
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
// 根据类型添加基于自动装配的属性值
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 存在实例化时适用的后置处理器
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
// 赋值前: 再次获取InstantiationAwareBeanPostProcessor,存在则执行postProcessPropertyValues()
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 后置处理bean属性值
// 在工厂将给定的属性值应用于给定的 bean 之前对其进行后处理。
// 允许检查是否所有依赖项都已满足,例如基于 bean 属性设置器上的“必需”注释。
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
// 最后进行依赖检查
if (needsDepCheck) {
if (filteredPds == null) {
// 从beanWrapper 中提取一组过滤的 PropertyDescriptor,
// 不包括忽略的依赖类型或定义在忽略的依赖接口上的属性
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 执行依赖项检查以确保所有公开的属性都已设置。
// 依赖项检查可以是对象(协作 bean)、简单的(基元和字符串)或全部(两者)
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
// 应用给定的属性值,解析对此 bean 工厂中其他 bean 的任何运行时引用。
// 必须使用深拷贝,所以我们不会永久修改这个属性
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
/**
* Fill in any missing property values with references to
* other beans in this factory if autowire is set to "byName".
* @param beanName the name of the bean we're wiring up.
* Useful for debugging messages; not used functionally.
* @param mbd bean definition to update through autowiring
* @param bw the BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
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");
}
}
}
}
/**
* Abstract method defining "autowire by type" (bean properties by type) behavior.
* <p>This is like PicoContainer default, in which there must be exactly one bean
* of the property type in the bean factory. This makes bean factories simple to
* configure for small namespaces, but doesn't work as well as standard Spring
* behavior for bigger applications.
* @param beanName the name of the bean to autowire by type
* @param mbd the merged bean definition to update through autowiring
* @param bw the BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is an unsatisfied, non-simple property.
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
initializeBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
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/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(String beanName, Object bean, { RootBeanDefinition mbd)
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
// 判断并执行 BeanNameAware, BeanClassLoaderAware, BeanFactoryAware 三个子接口
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
// RootBeanDefinition.isSynthetic : 此 bean 定义是否是“合成的”,即不是由应用程序本身定义的
if (mbd == null || !mbd.isSynthetic()) {
// 如果不是合并的bean,在初始化之前执行 Bean 后处理器,调用其 BeanPostProcessor.postProcessBeforeInitialization 方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行实现了InitializingBean 或 @Bean(initMethod = "init_method")的Bean的 初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 如果不是合并的bean,在初始化之前执行 Bean 后处理器,调用其 初始化之后执行BeanPostProcessor.postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
private void invokeAwareMethods(String beanName, 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);
}
}
}
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// ApplicationContextAwareProcessor剩余实现aware接口的Bean的处理
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
protected void invokeInitMethods(String beanName, Object bean, RootBeanDefinition mbd)
throws Throwable {
// 如果实现了InitializingBean,调用其实现的afterPropertiesSet()方法
// 同时要注意如果实现了InitializingBean的afterPropertiesSet的方法,
// 那么就指定初始化方法名(init-method)不能和 afterPropertiesSet重名
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
// 调用其指定的初始化方法
String initMethodName = mbd.getInitMethodName();
// 执行初始化方法的前提条件是
// 1 - 不能实现InitializingBean
// 2 - 指定的初始化方法名不能是afterPropertiesSet
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.hasAnyExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
//AOP处理
public Object postProcessAfterInitialization( { Object bean, String beanName)
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
//返回代理类
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
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
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/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning
// 清除ResoureLoader缓存
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 初始化和生命周期相关的后置处理器,在容器中获取LifecycleProcessor 类型的后置处理器接口,在容器刷新完成以及关闭时执行的方法
// 如果没有会注册一个默认的生命周期组件
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 拿到生命周期处理器,回调onRefresh()容器刷新完成方法
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布 容器刷新完成事件 ContextRefreshedEvent
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
// 向MBeanServer托管Live Beans
if (!NativeDetector.inNativeImage()) {
LiveBeansView.registerApplicationContext(this);
}
}
/**
* Initialize the LifecycleProcessor.
* Uses DefaultLifecycleProcessor if none defined in the context.
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
this.lifecycleProcessor =
beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
if (logger.isTraceEnabled()) {
logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
}
}
else {
DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
defaultProcessor.setBeanFactory(beanFactory);
this.lifecycleProcessor = defaultProcessor;
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
if (logger.isTraceEnabled()) {
logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " +
"[" + this.lifecycleProcessor.getClass().getSimpleName() + "]");
}
}
}
destroyBeans()
org.springframework.context.support.AbstractApplicationContext#destroyBeans
1
2
3
4
5
6
7
8
9
10
11
12
13
14/**
* Template method for destroying all beans that this context manages.
* The default implementation destroy all cached singletons in this context,
* invoking {@code DisposableBean.destroy()} and/or the specified
* "destroy-method".
* <p>Can be overridden to add context-specific bean destruction steps
* right before or right after standard singleton destruction,
* while the context's BeanFactory is still active.
* @see #getBeanFactory()
* @see org.springframework.beans.factory.config.ConfigurableBeanFactory#destroySingletons()
*/
protected void destroyBeans() {
getBeanFactory().destroySingletons();
}
cancelRefresh(ex)
org.springframework.context.support.AbstractApplicationContext#cancelRefresh
1
2
3
4
5
6
7
8/**
* Cancel this context's refresh attempt, resetting the {@code active} flag
* after an exception got thrown.
* @param ex the exception that led to the cancellation
*/
protected void cancelRefresh(BeansException ex) {
this.active.set(false);
}
resetCommonCaches()
org.springframework.context.support.AbstractApplicationContext#resetCommonCaches
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18/**
* 清空产生的缓存数据
*
* Reset Spring's common reflection metadata caches, in particular the
* {@link ReflectionUtils}, {@link AnnotationUtils}, {@link ResolvableType}
* and {@link CachedIntrospectionResults} caches.
* @since 4.2
* @see ReflectionUtils#clearCache()
* @see AnnotationUtils#clearCache()
* @see ResolvableType#clearCache()
* @see CachedIntrospectionResults#clearClassLoader(ClassLoader)
*/
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
source
AbstractApplicationContext (Spring Framework 5.3.22 API)
ApplicationStartup (Spring Framework 5.3.22 API)
SpringBoot源码解析之应用类型识别 - 腾讯云开发者社区-腾讯云 (tencent.com)
Spring Boot 项目启动分析 - JohnNiang’s Blog
解读Spring Boot启动过程之二:Web工程启动的主干流程 - i初学者 - 博客园 (cnblogs.com)
https://www.ai2news.com/blog/1586113
Spring refresh() 方法详解(启动Spring,bean的创建过程)_51CTO博客_spring refresh方法作用
[Spring源码解读(五)Bean创建过程之创建——AbstractAutowireCapableBeanFactory (csdn.net)
spring boot 启动流程 - 掘金 (juejin.cn)