springboot启动是通过一个main方法启动的,代码如下
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
从该方法我们一路跟进去,进入SpringApplication的构造函数,我们可以看到如下代码primarySources,为我们从run方法塞进来的主类,而resourceLoader此处为null,是通过构造函数重载进来,意味着这里还有其它方式的用法,先绕过。
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
所以我们来看SpringFactoriesLoader中的loadSpringFactories方法,先获取资源路径META-INF/spring.factories
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
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);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
for (Map.Entry<?, ?> entry : properties.entrySet()) {
String factoryClassName = ((String) entry.getKey()).trim();
for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryClassName, factoryName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
以上代码执行完成后形成的内容大概是这样的,key表示factoryClassName
result = new LinkedMultiValueMap<>();
list=new LinkList();
list.add("com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration");
list.add("org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration")
result.put("org.springframework.boot.autoconfigure.EnableAutoConfiguration",list);
所以此时回退到这个方法setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); 就是从遍历出来的所有的这些内容中获取出key为org.springframework.context.ApplicationContextInitializer 的集合 设置该当前类的initializers集合,后面的Listeners 集合也是一样的过程。只不过,后一次获取是从上一次的缓存中取的。
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
设置完initializer和listener集合后,进行主函数推断 接着看代码,此处对主函数的推断非常的巧妙,就是利用虚拟机运行时已被入栈的所有链路一路追踪到方法名为main的函数,然后获取到他的类名。
private Class<?> deduceMainApplicationClass() {
try {
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
}
return null;
}
此时已经将SpringApplication 对象new出来了,然后接着执行它的run方法,先总结下以上代码干了几个事情
- this.primarySources 设置了主类集合
- this.webApplicationType 设置了web容器类型
- setInitializers 设置了ApplicationContextInitializer
- setListeners 设置了ApplicationListener
- mainApplicationClass 设置了入口类
- 加载并且解析了所有的spring.factories文件并缓存起来,注意此时只是解析成属性。
我们发现一个奇怪的现象既然已经有了this.primarySources 为什么还要来个mainApplicationClass呢?mainApplicationClass目前看来除了日志打印以及banner之外没有什么其它作用。
接着看run方法
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
上述代码中在prepareContext阶段完成了第一阶段的beanDefinition注册,此处仅注册了第一bean 通过主类传进去的那个类。之后再refresh阶段,通过解析该类进行第二轮的beandefinition注册。这一部分属于spring-context的内容了。
在refresh阶段,因为主类作为一个配置类,自然也是需要进行一轮解析的,所以接下来的步骤就是解析@SpringbootApplication,此注解为一个复合注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
内容解析:
此处导入了一个AutoConfigurationImportSelector ,同时还通过@AutoConfigurationPackage导入了一个AutoConfigurationPackages.Registrar.class
而我们知道在spring的配置类(单一类)的解析过程中的顺序是
- 先解析Component系列的注解
- 再解析@PropertySource
- 接着解析@ComponentScan与@ComponentScans注解
- 接着解析@Import
- 接着解析ImportResource
- 最后解析@Bean注解
而再Import中又分为几种类型
- ImportSelector
- ImportBeanDefinitionRegistrar
- 普通的import类
他们的加载顺序为,普通的类–>importSelector–deferredImportSelector–>ImportResource–>ImportBeanDefinitionRegistrar 综上所述spring.factories声明的配置类看来也不是垫底解析的,所以如果有遇到需要顺序的场景可以参照这个顺序来声明即可。
|