目录
前言
追源码前的准备
正文
注解的讲解
启动流程源码分析
Spring boot启动的大致模型图
总结
课程推荐(免费)
前言
上篇帖子带小伙伴们入门了Spring boot,使用Spring boot搭建了一个hello world工程,也抛出了疑问,为什么Spring boot不需要任何的配置文件就能启动整个项目。所以本篇帖子从底层挖掘Spring boot如何帮你自动选型和自动配置!
追源码前的准备
1.对Spring boot底层有一个大概的了解,掌握Spring boot常用注解
2.准备好hello world项目代码(需要hello world代码的同学可以去上面链接的帖子复制)
3.能够熟练使用idea或者eclipse的debug工具(推荐idea)
4.追Spring boot一定要对Spring底层有一定的了解,掌握Spring常见的注解
5.找到debug的程序的入口(个人建议最好是自己先去找,找到头疼再去找帖子或者视频学习)
前三点算是追源码的万能公式把。
正文
注解的讲解
追源码前,先思考换成你来设计Spring boot你该如何设计?
作为一个脚手架来说,初衷肯定是为了去简化配置操作,所以肯定是整合后端开发常见的环境配置,以及开放一种规范给其他不常见的环境进行配置。那么我们把自动配置的代码写好后,岂不是项目已启动所有的配置都要生效,岂不是会很占用空间,我们可不可以根据用户选择了那些环境从而只生成那些环境的配置呢?
那么,我们该如何找到入口呢?
目前的入口在main方法的@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) })
public @interface SpringBootApplication {
上面4个注解是规范自带与我们关系不大,我们看到后面3个注解
@ComponentScan注解学过Spring的同学都应该明白,基于注解的形式注入到Spring的IOC容器中,要配置一个配置类来扫描注解,配合@Configuration注解一起使用,那么@Configuration在哪里呢?
看到@SpringBootConfiguration,我们先追进去
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
看到了@Configuration注解。然而3个重要注解我们已经追完2个了,并没有追到我们想要的东西,所以入口肯定是在@EnableAutoConfiguration注解中,所以我们追进去。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
老规矩,上面4个不重要,所以重要的再下面2个注解。先看到@AutoConfigurationPackage
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
重要的就只有@Import(AutoConfigurationPackages.Registrar.class)
追到AutoConfigurationPackages.Registrar.class中
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
register(registry, new PackageImport(metadata).getPackageName());
}
@Override
public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.singleton(new PackageImport(metadata));
}
}
不用想都知道追到register()方法中去
其实追到这里就可以不需要往后走了,有看过Spring中IOC源码的同学就能看明白。
首先我们看到registerBeanDefinitions()方法中参数BeanDefinitionRegistry registry就能明白是把数据解析成BeanDefinition对象,并且另外一个参数是AnnotationMetadata metadata这里参数保存的是注解的一些元信息,也就是这个注解使用在哪里的一些信息。再看到register()方法中,就是把数据添加到BeanDefinition中,并且添加到集合中。
而我们追的是自动配置的源码,而这里是把使用注解的类解析成BeanDefinition添加到集合中准备后面注入到IOC容器中,跟我们想要的结果不一样,所以入口就是另外一个注解了@Import(AutoConfigurationImportSelector.class)。我们回到刚开始并且追进去。
@Import注解的作用
简单的说就是标有此注解的类使用注解括号中的配置类。
来到AutoConfigurationImportSelector类中,我们发现类很复杂,此时我们该如何找入口呢?
此时我们要想一下,自动配置肯定是在这里了,其他的路口我们都走完了并没有发现,所以我们在这里的出发点往自动配置的方法走。
此时我们打开全部方法ctrl+F12,我们可以看到有一个getAutoConfigurationEntry()方法,而这个方法又被selectImports()给调用。而selectImports是重写ImportSelector类的方法。此时我们就需要弄懂ImportSelector类的作用,此时我们发现并没有实现ImportSelector,而看到实现了DeferredImportSelector类,所以我们需要弄懂ImportSelector和DeferredImportSelector类的关系
两者都是@Import注解的接口实现。也就是通过实现这两个接口也可以实现@Import的功能,但是他们两者的区别呢?
DeferredImportSelector:在@Configuration其他逻辑之后执行
ImportSelector:在@Configuration其他逻辑之前执行
所以我们知道通过selectImports()方法的返回值就能导入到Spring中。
所以我们就往getAutoConfigurationEntry()方法看。
再看到getCandidateConfigurations()。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
所以继续往loadFactoryNames()方法里面走。
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 factoryTypeName = ((String) entry.getKey()).trim();
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);
}
}
我们看到FACTORIES_RESOURCE_LOCATION常量,就能明白这里就是在解析自动配置,并且是通过检查META-INF文件夹下是否存在spring.fatories文件夹,而我们看到maven仓库。
就是在解析这些参数,但是我们要思考全部都会解析添加进去吗?
我们随便打开自动配置包下的路径
可以看到 @Conditional系列的标签在对是否添加做了判断,所以就可以证明并不是所有的自动配置都会添加到Spring boot中。
但是随着版本的更新迭代,反正在Spring boot2.2.1版本并不是走这个流程了。我们再思考不走这里还能走哪里呢?
目前唯一没有看的推测的代码就是main()方法中的方法,而main()方法中的代码也就是Spring boot启动的代码,所以我们追一下Spring boot启动源码的同步看否代替了这些步骤呢?
启动流程源码分析
给main()方法给上断点,然后debug开始运行项目。
我们看到SpringApplication()的构造方法
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();
}
对于执行流程我就直接讲重要的代码,并不会讲推理过程和对我们不重要的一些代码,这里我建议大家能追明白大概的同时去强化其他代码,因为存在即合理,其他代码可能是Spring boot和Spring的一些高扩展点!
看到setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));并来上一个断点跳到断点上并且继续追进去。
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
这里是不是跟前面讲解注解的代码比较相似呢?
这行来上断点追进去SpringFactoriesLoader.loadFactoryNames(type, classLoader)
继续往这个方法走loadSpringFactories(classLoader)
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 factoryTypeName = ((String) entry.getKey()).trim();
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);
}
}
这里跟注解哪里的代码一样,所以这里就可以证明在Spring boot启动的时候解析了
META-INF/spring.factories中配置的自动配置类的参数并且添加到缓存中。所以我们一路返回继续查看Spring boot后续启动做了一些什么。
// 这里是Spring boot的一些监听接口,高扩展罢了
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 这是找到main方法找哪里,因为我们在启动类中创建一个静态内部内写一个main方法也可以启动容器
this.mainApplicationClass = deduceMainApplicationClass();
刚刚只是SpringApplication构造方法进行的一些初始化步骤,然后我们继续往run()方法里面追。
public ConfigurableApplicationContext run(String... args) {
// 创建一个计时器
StopWatch stopWatch = new StopWatch();
// 计时器开始
stopWatch.start();
// 创建Spring的上下文对象,方便后面对Spring boot解析的数据给添加到IOC容器中
ConfigurableApplicationContext context = null;
// Spring boot的异常
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
// 配置一些项目中的环境变量
configureHeadlessProperty();
//获取到事件监听器,并且获取到之前的解析的事件开始监听
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
// args是我们的启动参数,所以这里也就是将我们的启动参数给封装
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//Spring boot的环境配置的一些预先处理,因为是web项目所以是servle环境
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
// 配置系统环境
configureIgnoreBeanInfo(environment);
// 控制台的Spring大logo的打印
Banner printedBanner = printBanner(environment);
// 获取到上下文容器(细讲)
context = createApplicationContext();
// Spring boot的异常处理
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 上下文容器的预处理,就是refresh之前的一些准备操作(细讲)
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// refresh操作(细讲)
refreshContext(context);
// refresh之后的一些操作
afterRefresh(context, applicationArguments);
// 启动时间结束并控制台打印耗时多久
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
// 调用监听的started方法 算是切换监听的状态
listeners.started(context);
// 完成容器启动后的一个ApplicationRunner或者CommandLineRunner回调
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;
}
核心代码都在这里了,都给上了注释,这里只会挑选核心重要的代码来讲解。
看到context = createApplicationContext();给上一个断点,调到这行断点上并且进入。
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
可以看到使用到switch case的语法来判断用哪个ConfigurableApplicationContext 的实例对象。
因为我们是web项目,所以肯定是SERVLET,此时就是通过反射来获取到Servlet的ApplicationContext的实例对象,所以我们看到DEFAULT_SERVLET_WEB_CONTEXT_CLASS常数值
此时使用idea快捷键连按2下shift全局搜索AnnotationConfigServletWebServerApplicationContext
进来以后,我们发现有三个构造方法,我们全给上断点,看他默认执行那个构造方法,我们直接断点放行,直接来到了无参构造方法。
public AnnotationConfigServletWebServerApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
再继续往下之前我认为得弄清楚AnnotationConfigServletWebServerApplicationContext类关系图
关系很复杂,所以证明Spring系列的框架对接口设计非常的细腻扩展点也非常的高。
我们知道只要继承或者是实现了类,就可以拥有父类的全部,所以只要在原本的基础下继承下来再对其扩展。
我们来看看他的父类ServletWebServerApplicationContext
我们可以看到WebServer
其实就能明白这里这里对我们的项目启动的tomcat进行了封装。
再往上的父类观察一下
可以看到这里管理ServletContext上下文
再往上的父类查看一下
发现这里维护了BeanFactory对象,有了BeanFactory岂不是能为所欲为了?
所以Spring系列的源码虽然追起来头疼,继承关系非常的复杂,但是他的扩展是真的牛。
我们回到我们的SpringApplication类中的run方法中给refreshContext()打上断点非常核心的方法。
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
继续进入到refresh()方法
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
ApplicationContext是我们之前反射获取AnnotationConfigServletWebServerApplicationContext。
继续追进refresh()方法
@Override
public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
stopAndReleaseWebServer();
throw ex;
}
}
注意到super.refresh()方法,super关键字大家都明白是调用父类的方法。我们追进去。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
看过Spring源码的小伙伴应该对这个方法已经熟的不能再熟悉了,这里就是一些回调方法,一些方法具体的实现基于实现类中的实现。
此时已经来到了Spring的核心类了,已经不再是Spring boot的类了,所以这里就是把Spring boot解析好的内容通过refresh()方法添加到IOC容器中。
我们看到onRefresh()方法给上一个断点,因为ServletWebServerApplicationContext类重写了此方法,通过此方法初始化一些内容。我们直接放行到onRefresh()
@Override
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
super.onRefresh()没啥内容,跟我们关系不大,注意到createWebServer()方法我们追进去。
private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}
此时我们的WebServer是空的,并且ServletContext也是空,并没有对其初始化,所以我们进入到第一个if代码块中。
ServletWebServerFactory factory = getWebServerFactory();是将我们的tomcat封装对象注入到IOC容器中,再往下进入到factory.getWebServer(getSelfInitializer());方法中
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
if (this.disableMBeanRegistry) {
Registry.disableRegistry();
}
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
Connector connector = new Connector(this.protocol);
connector.setThrowOnFailure(true);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}
没错就是对tomcat对象进行一个初始化,我们进入到getTomcatWebServer()方法中。
对其一个初始化和启动tomcat容器。
我们可以看到我们的控制已经输出响应的一个tomcat启动的日志了。
然后就回到refresh()方法中的finishBeanFactoryInitialization(beanFactory);这个就是把beanDefinitionNames集合中的BeanDefinition对象给注入到IOC容器中,创建Bean和添加到容器中的代码这里不多说,可以看博主的Spring IOC容器启动源码解析
接着往下走refresh()方法全部执行完一路返回就回到了SpringApplication类中的refreshContext()context.registerShutdownHook();大致就是一个钩子函数,项目运行结束时触发,类容就是创建了一个销毁线程,内容就是close一个资源。我们接着返回。
回到了SpringApplication中的run()方法了,后续没什么重要的内容就是对启动的时间做一个处理输出在控制台,然后事件监听器切换到started状态再切换到running状态。
然后就是判断是否重现ApplicationRunner和CommandLineRunner接口也是一个钩子函数,执行这里方法也是run()方法最后的一个方法,所以就是启动结束后的一个回调函数,也是一个高扩展点。
Spring boot启动的大致模型图
总结
其实追源码前能自己宏观猜测里面的大致步骤是什么,再进去追源码就容易很多。
下节内容手写配置让Spring boot扫描添加到IOC容器中。