SpringBoot源码解析-启动流程(一)

1,178 阅读3分钟

前言: 读过spring源码的读者应该知道,spring源码有一个特点就是从顶层看,逻辑并不复杂。但是深入了看,spring为了实现一个逻辑会做大量的工作。想要一下子找到spring一个逻辑的源头并不容易。

所以我建议在分析源码的时候会使用层层突进,重点突破的策略。千万别 看到一个方法就钻进去,这样很容易迷失在代码中。


搭建项目应该不用多说了吧,使用idea 的spring initalizer功能,选择web模块,一键就可以搭建好。自己写一个简单的controller,测试一下:

@RestController
public class Controller {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

}

打开浏览器,输入正确的地址。如果浏览器显示hello那项目就搭建成功了。

开始分析代码

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

    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);
	}

从springboot入口的run方法点进来,到了这儿。可以看到新建了一个SpringApplication对象,然后调用了该对象得到run方法。 所以我们一步一步来,这一节先分析新建的过程。

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");
		this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
		
		//判断web容器的类型
		this.webApplicationType = WebApplicationType.deduceFromClasspath();
		
		//初始化ApplicationContextInitializer实例
		setInitializers((Collection) getSpringFactoriesInstances(
				ApplicationContextInitializer.class));
				
		//初始化ApplicationListener实例
		setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
		
		//判断那个是入口类
		this.mainApplicationClass = deduceMainApplicationClass();
	}

新建代码如上,primarySources参数就是我们一开始传入的Application.class,resourceLoader为null。 前三行主要是校验以及设置参数。第四行,判断了web容器的类型,代码如下:

	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;
			}
		}
		return WebApplicationType.SERVLET;
	}

主要看加载的包中,是否存在相应的类。我们主要用的是web模块,这个地方返回的是WebApplicationType.SERVLET。

下面开始了初始化applicationContextInitializer实例,代码如下:

	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) {
		ClassLoader classLoader = getClassLoader();
		
		//关键地方,类名就是从这儿加载的
		Set<String> names = new LinkedHashSet<>(
				SpringFactoriesLoader.loadFactoryNames(type, classLoader));
				
		//实例化刚刚获取的类
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
				classLoader, args, names);
		//排序
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}
	
	//点开loadFactoryNames方法,继续打开loadSpringFactories方法
	private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        。。。

		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;
		}
        。。。
	}

可以看到在loadSpringFactories方法中加载了"META-INF/spring.factories"文件的信息,并将其存入了map里。然后在loadFactoryNames中依据类名获取了相应的集合。那么根据刚刚传进来的类名ApplicationContextInitializer,我们去瞧一瞧配置文件里配了啥。打开springboot的jar包,找到spring.factories文件,发现里面配置如下。

# 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

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

到这儿我们就发现了,原来setInitializers方法,就是找的这几个类。

继续往下看初始化ApplicationListener实例的方法,这个方法的逻辑和上面初始化ApplicationContextInitializer一模一样,所以就不详解了。只需要知道springboot到那个地方,找到了那几个类就可以。几个ApplicationListener类名如下:

# 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

最后还有一行代码

this.mainApplicationClass = deduceMainApplicationClass();

这行代码逻辑就是获取方法的调用栈,然后找到main方法的那个类。显然,这边的mainApplicationClass就算我们入口的那个Application类。

到这儿,SpringApplication新建过程就结束了。总结一下,在SpringApplication新建过程中,程序主要还是以设置属性为主。这些属性现在我们只需要知道他们是啥就行,后面再针对功能进行分析。


返回目录