目录
Spring启动入口的run()方法
一般SpringBoot项目启动的入口为:
@SpringBootApplication
public class StartApplication {
public static void main(String args[]){
SpringApplication.run(StartApplication.class,args);
}
}
其中run()方法为:
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class[]{primarySource}, args);
}
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}
由此可知,run方法主要包含了两步,首先实例化SpringApplication对象,之后调用run方法完成启动。
SpringApplication实例化流程
- 赋值成员变量resourceLoader
- 赋值成员变量primarySources
- 推断Web应用类型
- 加载并初始化ApplicationContextInitializer及相关类
- 加载并初始化ApplicationListener及相关类
- 推断main方法
public SpringApplication(Class<?>... primarySources) {
this((ResourceLoader)null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
//赋值成员变量resourceLoader
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//赋值成员变量primarySources
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
//推断Web应用类型
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//加载并初始化ApplicationContextInitializer及相关类
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
//加载并初始化ApplicationListener及相关类
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
//推断main方法
this.mainApplicationClass = this.deduceMainApplicationClass();
}
赋值成员变量resourceLoader
可以通过ResourceLoader指定需要加载的资源路径,一般采用默认路径;
赋值成员变量primarySources
传入的是springboot的入口类,能作为入口类的条件为被@EnableAutoConfiguration注解;
推断Web应用类型
其中web应用类型一共有三种:
- NONE
- SERVLET
- REACTIVE
判断的方法为:
private static final String[] SERVLET_INDICATOR_CLASSES = new String[]{"javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext"};
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent("org.springframework.web.reactive.DispatcherHandler", (ClassLoader)null) && !ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", (ClassLoader)null) && !ClassUtils.isPresent("org.glassfish.jersey.servlet.ServletContainer", (ClassLoader)null)) {
return REACTIVE;
} else {
String[] var0 = SERVLET_INDICATOR_CLASSES;
int var1 = var0.length;
for(int var2 = 0; var2 < var1; ++var2) {
String className = var0[var2];
if (!ClassUtils.isPresent(className, (ClassLoader)null)) {
return NONE;
}
}
return SERVLET;
}
}
由此可以推断出三种类型的判断条件
加载并初始化ApplicationContextInitializer及相关类
ApplicationContextInitializer接口是Spring容器执行refreshed之前的一次回调。允许我们在Spring容器做进一步的控制和设置。
加载过程主要分为两个步骤,getSpringFactoriesInstances和setInitializers;
getSpringFactoriesInstances
其中,getSpringFactoriesInstances源码为:
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return this.getSpringFactoriesInstances(type, new Class[0]);
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = this.getClassLoader();
Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
该方法通过loadFactoryNames方法获得META-INF/spring.factories文件中ApplicationContextInitializer的全部相关实现类,之后通过createSpringFactoriesInstances方法对相应的类进行实例化操作:
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) {
List<T> instances = new ArrayList(names.size());
Iterator var7 = names.iterator();
while(var7.hasNext()) {
String name = (String)var7.next();
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
T instance = BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
} catch (Throwable var12) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12);
}
}
return instances;
}
setInitializers
该方法将实例化的集合向initializers赋值
public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList();
this.initializers.addAll(initializers);
}
加载并初始化ApplicationListener及相关类
ApplicationListener的加载过程与ApplicationContextInitializer基本一致,该接口定义了onApplicationEvent方法,如果监听的ApplicationEvent事件被触发,则监听器的onApplicationEvent方法会被调用。
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}
推断main方法
推断main方法用的是deduceMainApplicationClass方法:先创建一个运行时异常,然后获得栈数组,遍历栈数组,判断类中是否有main方法,如果有则创建对象并返回。
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = (new RuntimeException()).getStackTrace();
StackTraceElement[] var2 = stackTrace;
int var3 = stackTrace.length;
for(int var4 = 0; var4 < var3; ++var4) {
StackTraceElement stackTraceElement = var2[var4];
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
} catch (ClassNotFoundException var6) {
}
return null;
}
参考
(《Spring Boot 技术内幕》)