springboot啥都不难,总所周知spring全家桶系列难就难在理解源码。。。。。。。

今天结合网上资料,自己总结了一下springboot的自动配置原理。

我现在使用的springboot版本为2.3.1.不同版本的springboot在源码上有差别!但大体一致。



管他三七二十一先打个断点再说:

1.1 @SpringBootApplication

这个注解点进去我们可以看到:



这里面主要关注两个东西:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration

    第一个注解点进去:



    可以看到这个@SpringBootConfiguration本质就是一个@Configuration,标注在某个类上,表示这是一个Spring Boot的配置类。

    第二个注解@EnableAutoConfiguration: 开启自动配置类,SpringBoot的精华所在。(最重要的就是这个注解)

2.1 @EnableAutoConfiguration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {};
}

两个比较重要的注解:

  • @AutoConfigurationPackage:自动配置包。
  • @Import({AutoConfigurationImportSelector.class}):导入自动配置的组件。

2.1.1 @AutoConfigurationPackage

点进去瞅瞅:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
String[] basePackages() default {}; Class<?>[] basePackageClasses() default {};
}

发现这里有导入Regitstrar类:

static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
Registrar() {
} public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));
} public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.singleton(new AutoConfigurationPackages.PackageImports(metadata));
}
}

new PackageImport(metadata).getPackageName(),它其实返回了当前主程序类的 **同级以及子级 ** 的包组件。

什么意思呢?

我们来看这样一个目录:



bean1和我们的springboot启动类位于同一个包下,二bean2不是位于我们启动类的同级目录或者子级目录,那么我们启动的时候bean2是不会被加载到的!所以你项目的一切需要加入容器的类必须放在启动类的同级包下或者它的子级目录中。

2.1.2 @Import({Registrar.class})

AutoConfigurationImportSelector有一个方法为:selectImports。

public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}

它首先回去检查是否开启了自动配置类,然后才回去加载注解数据 this.getAutoConfigurationEntry(annotationMetadata);

那么这个annotationMetadata在哪儿?

来看下面一行代码:

  protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.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;
}

SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

再点进去我们会发现这一行代码:

Enumeration urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");

它其实是去加载 public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";外部文件。这个外部文件,有很多自动配置的类。如下:



spring.factories文件由一组一组的key=value的形式,其中一个key是EnableAutoConfiguration类的全类名,而它的value是一个xxxxAutoConfiguration的类名的列表,这些类名以逗号分隔。

springboot项目启动时,@SpringBootApplication用在启动类在SpringApplication.run(...)的内部就会执行selectImports()方法,找到所有JavaConfig自动配置类的全限定名对应的class,然后将所有自动配置类加载到Spring容器中。

3.1 以HttpEncodingAutoConfiguration为例

@Configuration(
proxyBeanMethods = false
) //表示是一个配置类,可以给容器中添加组件
@EnableConfigurationProperties({ServerProperties.class})// 启用ConfigurationProperties功能
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
prefix = "server.servlet.encoding",
value = {"enabled"},
matchIfMissing = true
)

@EnableConfigurationProperties({ServerProperties.class})// 启用ConfigurationProperties功能

ServerProperties.class:

@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)

@ConditionalOnWebApplication :spring底层@Conditional注解,根据不同的条件进行判断,如果满足条件整个配置类才会生效。

总结:

1.springboot会自动加载大量的自动配置类。

2.只要我们要用的组件有,我们就不需要再去配置

3.给容器添加组件的时候。会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性。

xxxxxAutoConfiguration:自动配置类

给容器中添加属性:

xxxxProperties:封装配置文件中的相关属性。

springboot_自动配置原理的更多相关文章

  1. spring boot实战(第十三篇)自动配置原理分析

    前言 spring Boot中引入了自动配置,让开发者利用起来更加的简便.快捷,本篇讲利用RabbitMQ的自动配置为例讲分析下Spring Boot中的自动配置原理. 在上一篇末尾讲述了Spring ...

  2. SpringBoot自动配置原理

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

  3. SpringBoot的自动配置原理过程解析

    SpringBoot的最大好处就是实现了大部分的自动配置,使得开发者可以更多的关注于业务开发,避免繁琐的业务开发,但是SpringBoot如此好用的 自动注解过程着实让人忍不住的去了解一番,因为本文的 ...

  4. 3. SpringBoot ——自动配置原理浅析

    SpringBoot的功能之所以强大,离不开它的自动配置这一大特色.但估计很多人只是知其然而不知其所以然.下面本人对自动配置原理做一个分析: 在使用SpringBoot时我们通过引入不同的Starte ...

  5. spring boot 自动配置原理

    1).spring boot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration,先看一下启动类的main方法 public ConfigurableApplic ...

  6. Spring Boot 自动配置原理(精髓)

    一.自动配置原理(掌握) SpringBoot启动项目会加载主配置类@SpringBootApplication,开启@EnableAutoConfiguration自动配置功能 @EnableAut ...

  7. Spring Boot自动配置原理、实战

    Spring Boot自动配置原理 Spring Boot的自动配置注解是@EnableAutoConfiguration, 从上面的@Import的类可以找到下面自动加载自动配置的映射. org.s ...

  8. 5. SprigBoot自动配置原理

      配置文件到底能写什么?怎么写? 都可以在SpringBoot的官方文档中找到: 配置文件能配置的属性参照   1.自动配置原理: 1).SpringBoot启动的时候加载主配置类,开启了自动配置功 ...

  9. 3springboot:springboot配置文件(外部配置加载顺序、自动配置原理,@Conditional)

    1.外部配置加载顺序 SpringBoot也可以从以下位置加载配置: 优先级从高到低 高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置  1.命令行参数 所有的配置都可以在命令行上进行指定 ...

随机推荐

  1. 05 . Nginx的反向代理与负载均衡

    Nginx负载均衡 客户端的访问都被代理到后端的一台服务器上,最终会出现性能瓶颈,从而导致效率降低,前端用户的访问速度急速下降,要解决这个问题就需要添加多台httpd,同时承受大量并发连接,每台服务器 ...

  2. Rocket - debug - TLDebugModuleInner - Drive Custom Access

    https://mp.weixin.qq.com/s/1bIqzDYXM36MIfSsjvvYIw 简单介绍TLDebugModuleInner中的针对Custom的访问. 1. customNode ...

  3. [精华帖]Java接口怎么定义?如何使用?【实例讲解】

    [精华帖?]滑稽之谈||| 题目: 模拟电脑USB功能设备使用 1.定义USB接口,具备最基本的开启功能和关闭功能 2.定义电脑类,具有开机.关机以及使用usb设备功能 3.鼠标类.具有usb功能,并 ...

  4. Java实现 LeetCode 887 鸡蛋掉落(动态规划,谷歌面试题,蓝桥杯真题)

    887. 鸡蛋掉落 你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N 共有 N 层楼的建筑. 每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去. 你知道存在楼层 F ,满足 0 < ...

  5. Java实现 LeetCode 643 子数组最大平均数 I(滑动窗口)

    643. 子数组最大平均数 I 给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数. 示例 1: 输入: [1,12,-5,-6,50,3], k = 4 输出: 12.7 ...

  6. Java实现 LeetCode 120 三角形最小路径和

    120. 三角形最小路径和 给定一个三角形,找出自顶向下的最小路径和.每一步只能移动到下一行中相邻的结点上. 例如,给定三角形: [ [2], [3,4], [6,5,7], [4,1,8,3] ] ...

  7. Java实现 蓝桥杯 素因子去重

    素因子去重 问题描述 给定一个正整数n,求一个正整数p,满足p仅包含n的所有素因子,且每个素因子的次数不大于1 输入格式 一个整数,表示n 输出格式 输出一行,包含一个整数p. 样例输入 1000 样 ...

  8. Java实现LeetCode_0027_RemoveElement

    package javaLeetCode.primary; import java.util.Scanner; public class RemoveElement_27 { public stati ...

  9. Java实现 洛谷 P1008 三连击

    public class Main { public static void main(String[] args){ for(int i = 123; i <= 329; i++){ int[ ...

  10. Java实现第九届蓝桥杯倍数问题

    倍数问题 题目描述 [题目描述] 众所周知,小葱同学擅长计算,尤其擅长计算一个数是否是另外一个数的倍数.但小葱只擅长两个数的情况,当有很多个数之后就会比较苦恼.现在小葱给了你 n 个数,希望你从这 n ...