小伙伴们是否想起曾经被 SSM 整合支配的恐惧?相信不少小伙伴都是有过这样的经历的,一大堆配置问题,各类排除扫描,导入一个新的依赖又得添加新的配置。自从有了 SpringBoot 以后,咋们就起飞了!各类零配置开箱即用,而咱们之因此开发起来可以这么爽,自动配置的功劳少不了,今天咱们就一块儿来讨论一下 SpringBoot 自动配置原理。html
本文主要分为三大部分:java
SpringBoot 源码经常使用注解拾遗web
SpringBoot 启动过程spring
SpringBoot 自动配置原理数组
这部分主要讲一下 SpringBoot 源码中常用到的注解,以扫清后面阅读源码时候的障碍。app
当可能大量同时使用到几个注解到同一个类上,就能够考虑将这几个注解到别的注解上。被注解的注解咱们就称之为组合注解。less
元注解:能够注解到别的注解上的注解。ide
组合注解:被注解的注解咱们就称之为组合注解。spring-boot
@Value
就至关于传统 xml 配置文件中的 value 字段。源码分析
假设存在代码:
@Component
public class Person {
@Value("i am name")
private String name;
}
复制代码
上面代码等价于的配置文件:
<bean class="Person">
<property name ="name" value="i am name"></property>
</bean>
复制代码
咱们知道配置文件中的 value 的取值能够是:
字面量
经过 ${key}
方式从环境变量中获取值
经过 ${key}
方式全局配置文件中获取值
#{SpEL}
因此,咱们就能够经过
@Value(${key})
的方式获取全局配置文件中的指定配置项。
若是咱们须要取 N 个配置项,经过 @Value 的方式去配置项须要一个一个去取,这就显得有点 low 了。咱们可使用 @ConfigurationProperties
。
标有
@ConfigurationProperties
的类的全部属性和配置文件中相关的配置项进行绑定。(默认从全局配置文件中获取配置值),绑定以后咱们就能够经过这个类去访问全局配置文件中的属性值了。
下面看一个实例:
person.name=kundy
person.age=13
person.sex=male
复制代码
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private String sex;
}
复制代码
这里 @ConfigurationProperties 有一个
prefix
参数,主要是用来指定该配置项在配置文件中的前缀。
@Import
注解支持导入普通 java 类,并将其声明成一个bean。主要用于将多个分散的 java config 配置类融合成一个更大的 config 类。
@Import
注解在 4.2 以前只支持导入配置类。
在4.2以后 @Import
注解支持导入普通的 java 类,并将其声明成一个 bean。
**@Import 三种使用方式 **
直接导入普通的 Java 类。
配合自定义的 ImportSelector 使用。
配合 ImportBeanDefinitionRegistrar 使用。
public class Circle {
public void sayHi() {
System.out.println("Circle sayHi()");
}
}
复制代码
@Import({Circle.class})
@Configuration
public class MainConfig {
}
复制代码
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Circle circle = context.getBean(Circle.class);
circle.sayHi();
}
复制代码
Circle sayHi()
能够看到咱们顺利的从 IOC 容器中获取到了 Circle 对象,证实咱们在配置类中导入的 Circle 类,确实被声明为了一个 Bean。
ImportSelector
是一个接口,该接口中只有一个 selectImports 方法,用于返回全类名数组。因此利用该特性咱们能够给容器动态导入 N 个 Bean。
public class Triangle {
public void sayHi(){
System.out.println("Triangle sayHi()");
}
}
复制代码
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
return new String[]{"annotation.importannotation.waytwo.Triangle"};
}
}
复制代码
@Import({Circle.class,MyImportSelector.class})
@Configuration
public class MainConfigTwo {
}
复制代码
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigTwo.class);
Circle circle = context.getBean(Circle.class);
Triangle triangle = context.getBean(Triangle.class);
circle.sayHi();
triangle.sayHi();
}
复制代码
Circle sayHi()
Triangle sayHi()
能够看到 Triangle 对象也被 IOC 容器成功的实例化出来了。
ImportBeanDefinitionRegistrar
也是一个接口,它能够手动注册bean到容器中,从而咱们能够对类进行个性化的定制。(须要搭配 @Import 与 @Configuration 一块儿使用。)
public class Rectangle {
public void sayHi() {
System.out.println("Rectangle sayHi()");
}
}
复制代码
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Rectangle.class);
// 注册一个名字叫作 rectangle 的 bean
beanDefinitionRegistry.registerBeanDefinition("rectangle", rootBeanDefinition);
}
}
复制代码
@Import({Circle.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
@Configuration
public class MainConfigThree {
}
复制代码
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MainConfigThree.class);
Circle circle = context.getBean(Circle.class);
Triangle triangle = context.getBean(Triangle.class);
Rectangle rectangle = context.getBean(Rectangle.class);
circle.sayHi();
triangle.sayHi();
rectangle.sayHi();
}
复制代码
Circle sayHi()
Triangle sayHi()
Rectangle sayHi()
嗯对,Rectangle 对象也被注册进来了。
> @Conditional
注释能够实现只有在特定条件知足时才启用一些配置。
下面看一个简单的例子:
public class ConditionBean {
public void sayHi() {
System.out.println("ConditionBean sayHi()");
}
}
复制代码
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
return true;
}
}
复制代码
@Configuration
@Conditional(MyCondition.class)
public class ConditionConfig {
@Bean
public ConditionBean conditionBean(){
return new ConditionBean();
}
}
复制代码
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(ConditionConfig.class);
ConditionBean conditionBean = context.getBean(ConditionBean.class);
conditionBean.sayHi();
}
复制代码
由于 Condition 的 matches 方法直接返回了 true,配置类会生效,咱们能够把 matches 改为返回 false,则配置类就不会生效了。
除了自定义 Condition,Spring 还为咱们扩展了一些经常使用的 Condition。
扩展注解 | 做用 |
---|---|
ConditionalOnBean | 容器中存在指定 Bean,则生效。 |
ConditionalOnMissingBean | 容器中不存在指定 Bean,则生效。 |
ConditionalOnClass | 系统中有指定的类,则生效。 |
ConditionalOnMissingClass | 系统中没有指定的类,则生效。 |
ConditionalOnProperty | 系统中指定的属性是否有指定的值。 |
ConditionalOnWebApplication | 当前是web环境,则生效。 |
在看源码的过程当中,咱们会看到如下四个类的方法常常会被调用,咱们须要对一下几个类有点印象:
ApplicationContextInitializer
ApplicationRunner
CommandLineRunner
SpringApplicationRunListener
下面开始源码分析,先从 SpringBoot 的启动类的 run() 方法开始看,如下是调用链:SpringApplication.run()
-> run(new Class[]{primarySource}, args)
-> new SpringApplication(primarySources)).run(args)
。
一直在run,终于到重点了,咱们直接看 new SpringApplication(primarySources)).run(args)
这个方法。
上面的方法主要包括两大步骤:
建立 SpringApplication 对象。
运行 run() 方法。
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
this.sources = new LinkedHashSet();
this.bannerMode = Mode.CONSOLE;
this.logStartupInfo = true;
this.addCommandLineProperties = true;
this.addConversionService = true;
this.headless = true;
this.registerShutdownHook = true;
this.additionalProfiles = new HashSet();
this.isCustomEnvironment = false;
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
// 保存主配置类(这里是一个数组,说明能够有多个主配置类)
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
// 判断当前是不是一个 Web 应用
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 从类路径下找到 META/INF/Spring.factories 配置的全部 ApplicationContextInitializer,而后保存起来
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 从类路径下找到 META/INF/Spring.factories 配置的全部 ApplicationListener,而后保存起来
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
// 从多个配置类中找到有 main 方法的主配置类(只有一个)
this.mainApplicationClass = this.deduceMainApplicationClass();
}
复制代码
public ConfigurableApplicationContext run(String... args) {
// 建立计时器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 声明 IOC 容器
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
// 从类路径下找到 META/INF/Spring.factories 获取 SpringApplicationRunListeners
SpringApplicationRunListeners listeners = this.getRunListeners(args);
// 回调全部 SpringApplicationRunListeners 的 starting() 方法
listeners.starting();
Collection exceptionReporters;
try {
// 封装命令行参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 准备环境,包括建立环境,建立环境完成后回调 SpringApplicationRunListeners#environmentPrepared()方法,表示环境准备完成
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
// 打印 Banner
Banner printedBanner = this.printBanner(environment);
// 建立 IOC 容器(决定建立 web 的 IOC 容器仍是普通的 IOC 容器)
context = this.createApplicationContext();
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
/* * 准备上下文环境,将 environment 保存到 IOC 容器中,而且调用 applyInitializers() 方法 * applyInitializers() 方法回调以前保存的全部的 ApplicationContextInitializer 的 initialize() 方法 * 而后回调全部的 SpringApplicationRunListener#contextPrepared() 方法 * 最后回调全部的 SpringApplicationRunListener#contextLoaded() 方法 */
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 刷新容器,IOC 容器初始化(若是是 Web 应用还会建立嵌入式的 Tomcat),扫描、建立、加载全部组件的地方
this.refreshContext(context);
// 从 IOC 容器中获取全部的 ApplicationRunner 和 CommandLineRunner 进行回调
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
// 调用 全部 SpringApplicationRunListeners#started()方法
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
listeners.running(context);
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
复制代码
小结:
run() 阶段主要就是回调本节开头提到过的4个监听器中的方法与加载项目中组件到 IOC 容器中,而全部须要回调的监听器都是从类路径下的
META/INF/Spring.factories
中获取,从而达到启动先后的各类定制操做。
SpringBoot 项目的一切都要从
@SpringBootApplication
这个注解开始提及。
@SpringBootApplication 标注在某个类上说明:
这个类是 SpringBoot 的主配置类。
SpringBoot 就应该运行这个类的 main 方法来启动 SpringBoot 应用。
该注解的定义以下:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
复制代码
能够看到 SpringBootApplication
注解是一个组合注解(关于组合注解文章的开头有讲到),其主要组合了一下三个注解:
@SpringBootConfiguration
:该注解表示这是一个 SpringBoot 的配置类,其实它就是一个 @Configuration 注解而已。
@ComponentScan
:开启组件扫描。
@EnableAutoConfiguration
:从名字就能够看出来,就是这个类开启自动配置的。嗯,自动配置的奥秘全都在这个注解里面。
先看该注解是怎么定义的:
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
复制代码
从字面意思理解就是自动配置包。点进去能够看到就是一个 @Import 注解:
@Import({Registrar.class})
,导入了一个 Registrar 的组件。关于 @Import 的用法文章上面也有介绍哦。
咱们在 Registrar 类中的 registerBeanDefinitions 方法上打上断点,能够看到返回了一个包名,该包名其实就是主配置类所在的包。
一句话:@AutoConfigurationPackage 注解就是将主配置类(@SpringBootConfiguration标注的类)的所在包及下面全部子包里面的全部组件扫描到Spring容器中。因此说,默认状况下主配置类包及子包之外的组件,Spring 容器是扫描不到的。
该注解给当前配置类导入另外的 N 个自动配置类。(该注解详细用法上文有说起)。
那具体的导入规则是什么呢?咱们来看一下源码。在开始看源码以前,先啰嗦两句。就像小马哥说的,咱们看源码不用所有都看,不用每一行代码都弄明白是什么意思,咱们只要抓住关键的地方就能够了。
咱们知道 AutoConfigurationImportSelector 的 selectImports 就是用来返回须要导入的组件的全类名数组的,那么如何获得这些数组呢?
在 selectImports 方法中调用了一个 getAutoConfigurationEntry() 方法。
因为篇幅问题我就不一一截图了,我直接告诉大家调用链:在 getAutoConfigurationEntry() -> getCandidateConfigurations() -> loadFactoryNames()。
在这里 loadFactoryNames() 方法传入了 EnableAutoConfiguration.class 这个参数。先记住这个参数,等下会用到。
loadFactoryNames() 中关键的三步:
从当前项目的类路径中获取全部 META-INF/spring.factories
这个文件下的信息。
将上面获取到的信息封装成一个 Map 返回。
从返回的 Map 中经过刚才传入的 EnableAutoConfiguration.class
参数,获取该 key 下的全部值。
听我这样说完可能会有点懵,咱们来看一下 META-INF/spring.factories
这类文件是什么就不懵了。固然在不少第三方依赖中都会有这个文件,通常每导入一个第三方的依赖,除了自己的jar包之外,还会有一个 xxx-spring-boot-autoConfigure
,这个就是第三方依赖本身编写的自动配置类。咱们如今就以 spring-boot-autocongigure 这个依赖来讲。
能够看到 EnableAutoConfiguration 下面有不少类,这些就是咱们项目进行自动配置的类。
一句话:将类路径下 META-INF/spring.factories
里面配置的全部 EnableAutoConfiguration 的值加入到 Spring 容器中。
经过上面方式,全部的自动配置类就被导进主配置类中了。可是这么多的配置类,明显有不少自动配置咱们日常是没有使用到的,没理由所有都生效吧。
接下来咱们以 HttpEncodingAutoConfiguration
为例来看一个自动配置类是怎么工做的。为啥选这个类呢?主要是这个类比较的简单典型。
先看一下该类标有的注解:
@Configuration
@EnableConfigurationProperties({HttpProperties.class})
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
prefix = "spring.http.encoding",
value = {"enabled"},
matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
复制代码
@Configuration:标记为配置类。
@ConditionalOnWebApplication:web应用下才生效。
@ConditionalOnClass:指定的类(依赖)存在才生效。
@ConditionalOnProperty:主配置文件中存在指定的属性才生效。
@EnableConfigurationProperties({HttpProperties.class}):启动指定类的ConfigurationProperties功能;将配置文件中对应的值和 HttpProperties 绑定起来;并把 HttpProperties 加入到 IOC 容器中。
由于 @EnableConfigurationProperties({HttpProperties.class}) 把配置文件中的配置项与当前 HttpProperties 类绑定上了。而后在 HttpEncodingAutoConfiguration 中又引用了 HttpProperties ,因此最后就能在 HttpEncodingAutoConfiguration 中使用配置文件中的值了。最终经过 @Bean 和一些条件判断往容器中添加组件,实现自动配置。(固然该Bean中属性值是从 HttpProperties 中获取)
HttpProperties 经过 @ConfigurationProperties 注解将配置文件与自身属性绑定。
全部在配置文件中能配置的属性都是在 xxxProperties 类中封装着;配置文件能配置什么就能够参照某个功能对应的这个属性类。
@ConfigurationProperties(
prefix = "spring.http"
)// 从配置文件中获取指定的值和bean的属性进行绑定
public class HttpProperties {
复制代码
小结:
SpringBoot启动会加载大量的自动配置类。
咱们看须要的功能有没有SpringBoot默认写好的自动配置类。
咱们再来看这个自动配置类中到底配置了那些组件(只要咱们要用的组件有,咱们就不须要再来配置了)。
给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。咱们就能够在配置文件中指定这些属性的值。
xxxAutoConfiguration
:自动配置类给容器中添加组件。
xxxProperties
:封装配置文件中相关属性。
不知道小伙伴们有没有发现,不少须要待加载的类都放在类路径下的META-INF/Spring.factories
文件下,而不是直接写死这代码中,这样作就能够很方便咱们本身或者是第三方去扩展,咱们也能够实现本身 starter
,让SpringBoot 去加载。如今明白为何 SpringBoot 能够实现零配置,开箱即用了吧!
文章有点长,感谢你们的阅读!以为不错能够点个赞哦!
参考文章:
- www.cnblogs.com/duanxz/p/37…