spring boot啟動(dòng)包括2步, 1.生成SpringApplication對(duì)象, 2. 調(diào)用run方法.過(guò)程中包括Spring自有的 和SpringBoot獨(dú)有的一些步驟,系列文章將一步一步解析,能力有限,如果問(wèn)題請(qǐng)指出窘俺。本文解釋第一步過(guò)程, 下章解釋調(diào)用run方法.
1. 啟動(dòng)代碼
SpringApplication.run(DemoApplication.class, args);
2.生成SpringApplication對(duì)象
public SpringApplication(Object... sources) {
initialize(sources);
}
public SpringApplication(ResourceLoader resourceLoader, Object... sources) {
this.resourceLoader = resourceLoader;
initialize(sources);
}
i. SpringApplication 的構(gòu)造函數(shù)有2個(gè),
sources是要啟動(dòng)的類,一般調(diào)用run方法的類名.
resourceLoader是Spring 中用來(lái)加載資源文件的類,默認(rèn)實(shí)現(xiàn)是DefaultResourceLoader類, web環(huán)境下還有ServletContextResourceLoader
ii. initialize-初始化
初始分為5步,主要是為各種私有變量賦值.
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = deduceWebEnvironment();
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
a. 將sources 加入Set<Object> sources中.
b. 判斷當(dāng)前允許的環(huán)境是否為web環(huán)境,各種加載的類中是否有 "javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext" 來(lái)判斷 兩者都存在表示為web環(huán)境 同時(shí)也可以在初始化完成之后,run方法調(diào)用之前,通過(guò)setWebEnvironment改變.
c. 生成默認(rèn)ApplicationContextInitializer的父類Initializer.
d. 生成默認(rèn)ApplicationListener 的父類listener.
e. 判讀main函數(shù)在那個(gè)類中 ,所以在SpringBoot的工程中最好只有1個(gè)main方法妈踊。用的是StackTraceElement ,可以調(diào)用棧的信息,進(jìn)而遍歷出main方法.
3.解析spring.factories 獲取需要加載的 Initializer 和 listener
在第2步c 和d 的步驟中 需要加載默認(rèn)Initializer 和 listener ,是判斷所有jar包中的META-INF/spring.factories ,進(jìn)而取出ApplicationContextInitializer 或者 ApplicationListener 的父類枉证,然后實(shí)例化归敬。
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<String>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = new ArrayList<T>(names.size());
// Create instances from the names
for (String name : names) {
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass.getConstructor(parameterTypes);
T instance = (T) constructor.newInstance(args);
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : "
+ name, ex);
}
}
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
try {
Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
List<String> result = new ArrayList<String>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
String factoryClassNames = properties.getProperty(factoryClassName);
result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
}
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
如果需要加載自己的Initializer 和 listener有兩種方式可以實(shí)現(xiàn):在spring.factories 中增加,或者 通過(guò)addInitializers addListeners來(lái)增加。
4.后記
至此谆趾,SpringBoot 生成對(duì)象的結(jié)束了,后續(xù)可以set一些獨(dú)特的配置,比如web環(huán)境,自定義的 Initializer 和 listener, 最后調(diào)用run 方法,進(jìn)行bean初始化構(gòu)造,config加載等,下一章進(jìn)行詳細(xì)介紹巩梢。