SpringBoot原理

SpringBoot原理

七月 16, 2019

探究HelloWorld

pom文件

父项目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.21.RELEASE</version>
</parent>

<!--他的父项目如下,真正管理所有依赖-->

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.21.RELEASE</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
<!--spring-boot-dependencies真正管理所有依赖-->

由此,导入依赖不用写版本(特殊的,无管理的,需要声明版本号)

导入的依赖

1
2
3
4
5
6
7
<!--场景启动器-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

spring-boot-starter-web:导入Web模块相关的依赖

主程序类

SpringBootApplication

@SpringBootApplication标注在某个类上,说明该基类是SpringBoot的主配置类运行该类的main方法来启动SpringBoot应用

该注解为一个组合注解,如下代码所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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}
)}
)

@SpringBootConfiguration(SpringBoot的配置类):

​ 标注在某个类上,表示一个配置类;

@Configuration配置类上标注这个注解;

​ 配置类相当于配置文件,也是容器中的一个组件;

@EnableAutoConfiguration(开启自动配置):

​ 简化了手动配置,让SpringBoot帮助我们配置,利用该注解开启自动配置功能,该注解也是个组合注解;

1
2
@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})

@AutoConfigurationPackage(自动配置包)

​ @Import({Registrar.class})public @interface AutoConfigurationPackage {}

​ Spring中的底层注解,给容器中导入一个组件,作用:将主配置类的所在包及所有子包所有组件扫描至Spring容器中

EnableAutoConfigurationImportSelector(导入选择器)

​ 将所有需要导入的组件以全类名的方式返回,利用selectImports方法,返回一个String[],就会被添加到容器中;会给容器中导入非常多的自动配置类(xxxxAutoConfiguration),作用:给容器导入该场景所需要的所有组件,并配置好这些组件。

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

从类路径下META-INF/spring.factories中获取EnableAutoConfiguration指定的值;

J2EE整体整合解决方案和 自动配置都在\spring-boot-autoconfigure-1.5.21.RELEASE.jar!中

配置文件

作用

用来修改SpringBboot默认值

applicatio.properties

1
server.port=8081

application.yml

YAML是”YAML Ain’t a Markup Language”(YAML不是一种标记语言)的递归缩写。

标记语言:

​ 以前的配置文件大多以xxx.xml 文件;

​ YML以数据为中心,配置实例

1
2
server:
port: 8081

​ xml实例

1
2
3
<server>
<port>8081</port>
</server>

YAML相关语法参照YAML语法

相关用法

yml文件的注入测试

  1. 在你的项目中创建一个pojo类,构建一个实体类进行测试,属性包括:String类型,Interger类型,Boolean类型,Date类型,Map类型,List类型。注意,一定要写get&set方法

  2. 在你的配置文件pom.xml中需要如下几行代码,其作用:spring默认使用yml中的配置,但有时候要用传统的xml或properties配置,就需要使用spring-boot-configuration-processor了先引入pom依赖

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
    </dependency>
  3. 在你的yml中配置注入信息,如下所示

1
2
3
4
5
6
7
8
9
person:
lastName: zhangsan
age: 18
boss: false
birth: 2019/12/12
maps: {k1: v1,k2: v2}
lists:
- lisi
- zhaoliu
  1. 在你的实体类中添加两个注解

    1
    2
    @Component
    @ConfigurationProperties(prefix = "此处填yml文件中的最外层名字,按照上面的例子则应填person")
  2. 在test目录下进行单元测试,先先声明你的实体类对象,注意:需要加上@Autowired注解,在方法中输出所注入对象后的值即可如下代码所示

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    package com.run.ymltest;

    import com.run.ymltest.bean.Person;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;

    /**
    * SpringBoot单元测试
    */
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class YmlTestApplicationTests {
    @Autowired
    Person person;

    @Test
    public void contextLoads() {
    System.out.println("person = " + person);
    }

    }

properties文件的注入测试

将yml文件中的配置注释掉,在application.properties文件中写如下代码

1
2
3
4
5
6
7
8
9
person.last-name=张三
person.age=19
person.birth=2019/7/12
person.boss=true
person.maps.k1=vi
person.maps.k2=11
person.lists=1,1,2,3
person.dog.name=dog
person.dog.age=20

测试方法如上

此时有个问题是,中文出现乱码,properties文件编码方式与ide的编码有冲突,需要在idea中修改成utf8,然后勾选Transparent native-to-ascll

@Value获取值与@ConfigurationProperties获取值

@ConfigurationProperties @Value
功能 批量注入配置文件中的属性 只能一个一个指定
松散绑定(松散语法) 支持 不支持
SPEL(Spring表达式) 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装(map…) 支持 不支持

注:1、SPEL详情

2、数据校验,例子如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.run.ymltest.bean;


import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;


/*
将配置文件中的属性值映射到组件中
* */
@Component
@ConfigurationProperties(prefix = "person")
@Validated//开启JSR303数据校验
public class Person {
@Email//lastname必须是邮箱格式
// @Value("${person.last-name}")
private String lastName;
//以下省略

3、如果只是在逻辑业务中获取一下配置文件的某项值,使用@Value;如果专门编写了一个javaBean来和配置文件进行映射时,就直接使用@ConfigurationProperties;

@Property与@ImportResource

@Property加载指定的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@PropertySource(value = {"classpath:person.properties"})//加载默认配置文件
@Component
@ConfigurationProperties(prefix = "person")//默认从全局配置文件中获取值
//@Validated//开启JSR303数据校验
public class Person {
// @Email//lastname必须是邮箱格式
// @Value("${person.last-name}")
private String lastName;
// @Value("#{11*20}")
private Integer age;
// @Value("true")
private Boolean boss;
private Date birth;
//以下省略

@ImportResource导入Spring的配置文件,让配置文件里面的内容生效

SpringBoot里面,没有Spring的配置文件,自己的编写的配置文件不能自动识别,若想让Spring的配置生效,则需要利用该注解,将其标注在一个配置类上

1
@ImportResource(locations = {"classpath:beans.xml"})//加载所需配置文件

Spring原始添加组件方式

1
2
3
4
5
6
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.run.ymltest.service.HelloService"></bean>
</beans>

SpringBoot推荐给容器中添加组件的方式,推荐使用全注解的方式

配置类==Spring配置文件

1
2
3
4
5
6
7
8
9
@Configuration//指名当前类为配置类;替代之前的bean标签添加
public class MyConfig {
//将方法的返回值添加到容器中,id默认为方法名
@Bean
public HelloService helloService(){
System.out.println("配置类给容器中添加组件");
return new HelloService();
}
}

配置文件占位符

随机数

1
random.value、{random.int}、${random.long}、random.int(10)、{random.int[1024,65536]}

占位符获取之前配置的值,若没有可以用指定默认值

1
2
3
4
5
6
7
8
9
10
person.last-name=李四${random.uuid}
person.age=${random.int}
person.birth=2019/7/12
person.boss=true
person.maps.k1=vi
person.maps.k2=11
person.lists=1,1,2,3
#默认值:XXX
person.dog.name=${person.last-name:hello}_dog
person.dog.age=20

Profile

多Profile文件

在主配置文件编写时,文件名可以是application-{profile}.properties/yml

默认使用application.properties

yml支持多文档方式

利用yml中语法块模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#开启标识为prod的配置
spring:
profiles:
active: prod
---
server:
port: 8083
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod

激活指定profile

  1. 当使用application-dev.properties文件时,在主配置文件中利用如下方式启用
1
2
#启用标识为dev的配置文件时
spring.profiles.active=dev
  1. 使用命令行进行开启:

    打包前在Program arguments中传入–spring.profiles.active=dev命令行参数,便可开启标识为dev的配置(properties文件和yml文件一样适用)

    Z7taWR.png打包后,在cmd中可用如下命令开启指定配置

    1
    java -jar yml-test-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
  2. 虚拟机参数

    输入-Dspring.profiles.active=dev,便可开启

    Z7NV6x.png

配置文件加载位置

优先级由高到低,高优先级的会覆盖低优先级,只要存在,便都可以加载,形成互补配置

-file:./config/

-file:./

-classpath:/config/

-classpath:/

互补配置测试:

在优先级低的配置文件中输入如下代码进行测试,在网页中需要输入相应的路径才能访问

1
2
#配置项目的访问路径
server.servlet.context-path=/boot

spring.config.location

改变默认的配置文件位置

项目打包好后,使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定的和默认的会共同起作用,形成互补配置

外部配置的加载位置

SpringBoot可以从以下位置加载配置,优先级从高到低,高优先级的配置覆盖低优先级的配置,可形成互补配置

  1. 命令行参数(多个配置指令用空格隔开) java -jar 项目jar包名 –server.port=8088 –server.context.path=/boot

  2. 来自java:comp/env的JNDI属性

  3. Java系统属性(System.getProperties())
  4. 操作系统环境变量
  5. RandomValuePropertySource配置的random.*属性值优先加载带profile的,由jar外向内进行加载,覆盖:

由jar外向jar包内寻找

优先加载带profile

  1. jar包外部的application-{profile}.properties 或 application.yml(带spring.profile)配置文件
  2. jar包内部的application-{profile}.properties 或 application.yml(带spring.profile)配置文件
  3. jar包外部的application.properties 或 application.yml(不带spring.profile)配置文件
  4. jar包外部的application.properties 或 application.yml(不带spring.profile)配置文件
  5. @Configuration注解类上的@PropertySource
  6. 通过SpringApplication.setDefaultProperties指定的默认属性

自动配置原理

配置文件写什么:参照官方文档

自动配置原理

  1. SpringBoot启动时加载主配置类,开启自动配置功能@EnableAutoConfigration

  2. @EnableAutoConfigration作用:给容器中导入一些组件

    • 可以查看AutoConfigurationImportSelector.class中的内容
    1
    List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);//获取候选的配置
    • 1
      2
      3
      4
      SpringFactoriesLoader.loadFactoryNames
      扫描所有jar包路径下 META-INF/spring.factories
      把扫描到的这些文件内容包装成properties
      从properties中获取到EnableAutoConfigration.class类对应的值,然后把他们添加在容器中

      将类路径下META-INF/spring.factories里面配置的所有Enableconfiguration添加至文件中

      自动配置之源:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      # Auto Configure
      org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
      org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
      org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
      org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
      org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
      org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
      org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
      org.springframework.boot.autoconfigure.cloud.CloudServiceConnectorsAutoConfiguration,\
      org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
      org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
      org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
      org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
      org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
      org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
      org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
      org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
      org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
      org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
      org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
      org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
      org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
      org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
      org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
      org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
      org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
      org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
      org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
      org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
      org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
      org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
      org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
      org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
      org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
      org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
      org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
      org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
      org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
      org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
      org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
      org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
      org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
      org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
      org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
      org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
      org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
      org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
      org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
      org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
      org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
      org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
      org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
      org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
      org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
      org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
      org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
      org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
      org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
      org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
      org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
      org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
      org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
      org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
      org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
      org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
      org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
      org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
      org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
      org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
      org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
      org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
      org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

      每一个这样的xxxAutoConfiguration类都是容器中的一个组件,都添加到容器中,用他们来做自动配置

      1. 每一个自动配置类进行自动配置功能

      2. HttpEncodingAutoConfiguration为例

        所有在配置文件中能配置的属性都是在xxxproperties中封装;配置文件能配置什么就能参照某个功能对应的这个属性类

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        @Configuration//表示一个配置类,和配置文件一样,也可以给容器中添加组件
        @EnableConfigurationProperties({HttpProperties.class})//启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpProperties绑定起来;並且把httpEncodingProperties加入到spring容器中
        @ConditionalOnWebApplication(//spring底层Conditional注解,根据不同的条件,如果满足指定条件,整个配置类里面的配置才能生效; 判断是否是web应用
        type = Type.SERVLET
        )
        @ConditionalOnClass({CharacterEncodingFilter.class})//判断当前项目有没有这个类CharacterEncodingFilter springmvc中乱码解决过滤器
        @ConditionalOnProperty(//判断配置文件中是否存在某个配置spring.http.encoding.enabled
        prefix = "spring.http.encoding",//从配置文件中获取指定的值和bean的属性进行绑定
        value = {"enabled"},
        matchIfMissing = true
        )


        //他已經和springboot配置文件映射
        private final Encoding properties;

        //只有一個有參構造器的情況下,參數的值就會從容器里拿
        public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
        }

        @Bean//给容器中添加一个组件,組件的值從properties中獲得
        @ConditionalOnMissingBean
        public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
        }

        根据当前不同条件的判断,决定这个配置类是否生效

        一担这个配置类生效,这个配置类就会给容器中添加各种组件,这些组件是从对应的properties类中获取的,这些类的每个属性都是和配置文件绑定的

        精髓

        1. SpringBoot启动会加载大量的自动配置类
        2. 需要的功能是否已经默认写好相关配置类
        3. 再看自动配置了配了哪些组件
        4. 给自动配置类中添加组件时,能从properties类中获取某些属性值,就可以在配置文件中指定这些属性值