SpringBoot的功能之所以强大,离不开它的自动配置这一大特色。但估计很多人只是知其然而不知其所以然。下面本人对自动配置原理做一个分析:

在使用SpringBoot时我们通过引入不同的Starter,就自动地应用其相应的自动配置。这是由于每个Starter都会引一个相应xxx--autoconfigure.jar,并且在这个jar的META-INF/spring.factories文件中有类似如下的配置:

      org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

      org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

也就是通过org.springframework.boot.autoconfigure.EnableAutoConfiguration这个为 key引入自动配置类。这个自动类就会以代码的方式去完成以前Spring的xml配置文件做的事。

现在的关键问题就是,Spring的容器是如何知道这个自动配置类的存在的呢?带着这个问题,我们来跟踪SpringBoot启动类的实例run方法,先列出方法源码:

public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}

其实整个过程的秘密全在上面这段代码中体现出来了,只不过隐藏的比较深而已。上面这段有两个方法是和Spring容器发现这个自动配置类有关的

1. 在这个  prepareContext(context, environment, listeners, applicationArguments,printedBanner)    

          方法中完成了SpringBoot 的main方法中的启动类在Spring容器中的注册,并且是以源的方式进行注册。也就是相当于告诉spring容器,这个启动类就相当于是以前的xml文件了

2. refreshContext(context);    

       这个就是初始化 Spring容器,并实例化容器中注册的Bean,自然也就会对SpringBoot 的main方法中的启动类进行解析,这样一来,启动类上的 注解 @EnableAutoConfiguration就起作用了,但是要注意@EnableAutoConfiguration注解是springBoot提供的,springframeworke中的ApplicationContext是不会理会它的,而springboot接管后,相应的容器也是springBoot提供的,所以@EnableAutoConfiguration注解才会起作用,在createApplicationContext()中能看到springboot使用的容器类。

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

下面看 @EnableAutoConfiguration的源码:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; /**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {}; /**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {}; }

会发现这个 @EnableAutoConfiguration  注解里面 @Import(AutoConfigurationImportSelector.class) 

AutoConfigurationImportSelector里面有几段代码说明其会从META-INF/spring.factories文件,并加载其中配置key为org.springframework.boot.autoconfigure.EnableAutoConfiguration对应的类,我们称之为自动配置类,这样类上都会有@Configuration注解,所以就能被spring容器处理了。

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;
} /**
* Return the class used by {@link SpringFactoriesLoader} to load configuration
* candidates.
* @return the factory class
*/
protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}

 

 总结:

       @SpringBootApplication —— > @EnableAutoConfiguration ——> AutoConfigurationImportSelector——>META-INF/spring.factories

至此,一切真相大白。

3. SpringBoot ——自动配置原理浅析的更多相关文章

  1. 这样讲 SpringBoot 自动配置原理,你应该能明白了吧

    https://juejin.im/post/5ce5effb6fb9a07f0b039a14 前言 小伙伴们是否想起曾经被 SSM 整合支配的恐惧?相信很多小伙伴都是有过这样的经历的,一大堆配置问题 ...

  2. springboot自动配置原理以及手动实现配置类

    springboot自动配置原理以及手动实现配置类 1.原理 spring有一个思想是"约定大于配置". 配置类自动配置可以帮助开发人员更加专注于业务逻辑开发,springboot ...

  3. SpringBoot自动配置原理

    前言 只有光头才能变强. 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/ZhongFuCheng3y/3y 回顾前面Spring的文章(以学习的顺序排好): S ...

  4. SpringBoot实战之SpringBoot自动配置原理

    SpringBoot 自动配置主要通过 @EnableAutoConfiguration, @Conditional, @EnableConfigurationProperties 或者 @Confi ...

  5. SpringBoot自动配置原理学习

    介绍 构建Springboot项目时我们会创建一个启动类 @SpringBootApplication public class DemoApplication { public static voi ...

  6. 浅谈springboot自动配置原理

    前言 springboot自动配置关键在于@SpringBootApplication注解,启动类之所以作为项目启动的入口,也是因为该注解,下面浅谈下这个注解的作用和实现原理 @SpringBootA ...

  7. SpringBoot系列二:SpringBoot自动配置原理

    主程序类的注解 @SpringBootApplication 注解,它其实是个组合注解,源码如下: @Target({ElementType.TYPE}) @Retention(RetentionPo ...

  8. springBoot 自动配置原理--自己新建一个 starter

    上篇我们说到 springboot 和 SSM 框架的区别,今天我们就看看 springboot 到底为我们做了哪些事情,让我们开发变得如此简单. springboot 中起着重要作用的是 start ...

  9. springBoot 自动配置原理

    在之前文章中说过,springBoot会根据jar包去添加许多的自动配置,本文就来说说为什么会自动配置,自动配置的原理时什么? springBoot在运行SpringApplication对象实例化时 ...

随机推荐

  1. 2017-12-18python全栈9期第三天第三节之int bool str转换之数字转换成二进制的位数

    #!/user/bin/python# -*- coding:utf-8 -*-i= 100print(i.bit_length())

  2. SVN简单的使用

    一.什么是SVN有什么用? SVN是Subversion的简称,是一个开放源代码的版本控制系统.主要是用于团队开发中的资源共享和团队协作. 二.SVN服务器的安装 1.下载安装文件 在下面地址下载Vi ...

  3. [NIO-3]Socket通道

    Socket通道 上文讲述了通道.文件通道,这篇文章来讲述一下Socket通道,Socket通道与文件通道有着不一样的特征,分三点说: 1.NIO的Socket通道类可以运行于非阻塞模式并且是可选择的 ...

  4. Markdown Cheatsheet

    This is intended as a quick reference and showcase. For more complete info, see John Gruber's origin ...

  5. ELASTICSEARCH 搜索的评分机制

    从我们在elasticsearch复合框输入搜索语句到结果显示,展现给我们的是一个按score得分从高到底排好序的结果集.下面就来学习下elasticsearch怎样计算得分. Lucene(或 El ...

  6. 804. Unique Morse Code Words

    Description International Morse Code defines a standard encoding where each letter is mapped to a se ...

  7. 深入浅出mybatis之入门使用

    写在前面 mybatis是一个持久层框架,可以支持SQL定制和存储过程,实现数据库记录到Java POJO对象之间的映射. 所以说,mybatis是一个ORM框架. 这个ORM可以通过2种方式实现:x ...

  8. 对空间数据(Shape)重新排序

    打开ArcToolBox,数据管理工具->常规(General)->排序

  9. 设置 img 在 div 中水平居中和垂直居中

    Ø  前言 写 html + css 时,img 标签的垂直与水平居中,应该是很常见的设计.实现的方式很多,但是容易遗忘,下面分别整理了几种实现方式. 1.   css 代码 <style ty ...

  10. mysql 创建存储过程

    mysql 创建存储过程 实例一: CREATE PROCEDURE cp_test() BEGIN declare a int; declare b int; ; ; select a,b; END ...