logo头像

优秀是一种习惯

SpringApplication之初始化

本文于 363 天之前发表,文中内容可能已经过时。

SpringApplication之初始化 author: Tank

前言

当我们使用springboot时往往是以main方法起动,那main方法到底为我们做了什么呢?

1
2
3
4
5
6
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

SpringApplication (spring-boot的核心API)

当执行main方法时会调用springApplication的run方法.我们来看看 按调用顺序排列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
//这个方法只是把主配置源参数转了一下
public static ConfigurableApplicationContext run(Class<?> primarySource,
String... args) {

return run(new Class<?>[] { primarySource }, args);
}

//这个方法就是调用了SpringApplication 的有参构造器,创建一个SpringApplication的实例
public static ConfigurableApplicationContext run(Class<?>[] primarySources,
String[] args) {
return new SpringApplication(primarySources).run(args);
}
//===========过渡方法
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
//===========真正调用的是构造方法
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//给资源加载器属性赋值,但上面是null,所以这里其实为null
this.resourceLoader = resourceLoader;
//断言判断主配置类必须得有不然启动不了。(这个主配置类不一定是main方法的那个类。后续说明)
Assert.notNull(primarySources, "PrimarySources must not be null");
//给主配置源属性赋值
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//这里是推断出当前应用所属类型 类型有三种 NONE SERVLET REACTIVE
this.webApplicationType = deduceWebApplicationType();
//设置要初始化应用上下文所对应的对象 利用的是spring工厂加载机制
//从spring工厂内加载到的类以属性赋值的方式set到 initializers 内
//type = ApplicationContextInitializer 这个是类型
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
//设置初始化应用上下文后所对应的监听对象 利用的是spring工厂加载机制
//从spring工厂内加载到的监听器以属性赋值的方式set到 listeners 内
//type = ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(
ApplicationListener.class));
//推断出入口类 以属性赋值方式设置到mainApplicationClass
this.mainApplicationClass = deduceMainApplicationClass();
}


//============推断当前应用所属类型 这个方法简单,
//无非就是查一下有没有对应的类,如果有就返回对应的类型
private WebApplicationType deduceWebApplicationType() {
if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
&& !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_WEB_ENVIRONMENT_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : WEB_ENVIRONMENT_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}

//过渡方法
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
//type = ApplicationContextInitializer
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
//利用spring工厂加载 机制获取实例对象
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
//获取类加载器
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// 利用set特性保证不重复
Set<String> names = new LinkedHashSet<>(
//利用spring工厂加载器,根据类型加载对应的类名 具体逻辑请看SpringFactoriesLoader
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
//把从spring.factories内加载到的资源进行实例化
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
//排个序再返回
AnnotationAwareOrderComparator.sort(instances);
return instances;
}

//进行实例化
private <T> List<T> createSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, ClassLoader classLoader
, Object[] args,Set<String> names) {
List<T> instances = new ArrayList<>(names.size());
//对spring.factories内加载到的资源名遍历
for (String name : names) {
try {
//获取class对象
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
//断言判断一下是不是type的子类型
//比如 type = ApplicationContextInitializer
Assert.isAssignable(type, instanceClass);
//获取对应类型参数的构造器,由于前面并没有传参数,所以这里基本上调用的是无参构造器
Constructor<?> constructor = instanceClass
.getDeclaredConstructor(parameterTypes);
//利用BeanUtils 创建实例对象
T instance = (T) BeanUtils.instantiateClass(constructor, args);
//加入到列表再返回
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException(
"Cannot instantiate " + type + " : " + name, ex);
}
}
return instances;
}

//推断出入口类
private Class<?> deduceMainApplicationClass() {
try {
//从当前堆栈内循环比较方法名,如果有main方法的就当做入口类返回
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}

SpringFactoriesLoader (spring 的工厂加载器 这个是springframework的类)

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
//被加载资源路径
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

//根据名字找对应的属性
public static List<String> loadFactoryNames(
Class<?> factoryClass, @Nullable ClassLoader classLoader) {
//获取传进来的类的全类名 如:ApplicationContextInitializer
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader)
//如果有就返回,如果没有加载到就设置一个空list返回
.getOrDefault(factoryClassName,Collections.emptyList());
}
//加载
private static Map<String, List<String>> loadSpringFactories(
@Nullable ClassLoader classLoader) {
//先从本地缓存取,如果有直接返回
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
//这里有两个加载器,但是不管哪个加载器,加载的地址是一样的 FACTORIES_RESOURCE_LOCATION
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
//拿到URL"META-INF/spring.factories" 并new UrlResource 对象
// UrlResource 是一个根据路径获取资源的一个对象。
UrlResource resource = new UrlResource(url);
//使用Properties的工具类对这个路径下的文件进行读取并组成Properties对象
//spring.factories 请看下面
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
//组装成一个map返回 具体内容看下面的配置类
for (Map.Entry<?, ?> entry : properties.entrySet()) {
List<String> factoryClassNames = Arrays.asList(
StringUtils.commaDelimitedListToStringArray(
(String) entry.getValue()));
result.addAll((String) entry.getKey(), factoryClassNames);
}
}
//加入到缓存
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}

spring.factories (spring-boot 内建对象的配置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

#省略其他。。。

至此整个SpringApplication初始化完成。下一篇我们再来看初始化后是如何运行的。