常见spring boot 程序启动类中都是用
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
就是这么一句简单的代码,就构成了spring boot 的世界。我们从这一行开始学习。
run方法传入类主类及参数:
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class<?>[] { primarySource }, args);
}
接着调用如下代码:
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
//1、初始化SpringApplication对象,再调用run方法
return new SpringApplication(primarySources).run(args);
}
初始化SpringApplication对象:
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//将启动类加入此set
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//1、根据是否存在有些class,来推断出应用type
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//2、从META-INF/spring.factories文件中获取对应的类,并设置到属性中
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//3、根据method name 为main 来推断主类
//疑问:传进来的primarySources其实已经包含主类了,此处为何还要这样处理
this.mainApplicationClass = deduceMainApplicationClass();
}
初始化主要的两个操作:
deduceFromClasspath
即序号1处的代码,主要逻辑如下:
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
//常见的web应用中返回的是这个
return WebApplicationType.SERVLET;
}
WebApplicationType.SERVLET源码中的注释:The application should run as a servlet-based web application and should start an embedded servlet web server.
getSpringFactoriesInstances(序号2)
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
//1、获取ClassLoader
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
//2、加载名称并放入set中
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
//3、初始化
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
//4、排序操作
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
SpringFactoriesLoader.loadFactoryNames
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
//此时即是:org.springframework.context.ApplicationContextInitializer
String factoryTypeName = factoryType.getName();
//1、获取所有的配置,返回factoryTypeName对应的
return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
获取配置,即序号1对应的逻辑如下:
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
//尝试从缓存中获取:Map<ClassLoader, MultiValueMap<String, String>> cache
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
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();
UrlResource resource = new UrlResource(url);
//将spring.factories文件转为Properties,即key-value格式的
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryTypeName = ((String) entry.getKey()).trim();
//将spring.factories文件中按逗号分隔的value拆成list
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
此处包含的ApplicationContextInitializer如下:
# 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.rsocket.context.RSocketPortInfoApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
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());
for (String name : names) {
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
//调用构造器进行初始化,并加到instances进行返回
T instance = (T) BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
}
catch (Throwable ex) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
}
}
return instances;
}
setListeners方法,设置ApplicationListener的逻辑和这个一样,机调用getSpringFactoriesInstances加载META-INF/spring.factories中配置的org.springframework.context.ApplicationListener。对于当前来说,包含的类如下:
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
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
注意,这些Initializer和Listener在此处仅仅是初始化了,并没有执行其内部逻辑。
ApplicationListener接口
@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E var1);
}
此接口是函数式接口,onApplicationEvent的逻辑在prepareEnvironment(listeners, applicationArguments);方法中会回调。
ApplicationContextInitializer接口
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {
void initialize(C var1);
}
initialize方法在prepareContext() - applyInitializers(context) 方法中调用,用来对context做一些初始化。具体的逻辑后面还会解析到。