SpringBoot系列(二)---- 配置文件详解

配置文件

在SpringBoot中配置文件有两种,一种是application.properties,另一种是application.yml配置文件名是固定的。其中yml配置文件是在properties之后才有的。配置文件放在src/main/resources目录或者类路径/config下,配置文件的作用,就是修改SpringBoot自动配置的默认值,SpringBoot底层都给我们自动配置好了很多默认值,我们就需要通过灵活的使用properties和yml来进行修改默认配置。

我们通过Idea向导帮我们创建的新项目,在Resources目录下面会帮我们自动生成一个application.properties配置文件,如下图
在这里插入图片描述
在resources目录下我们可以暂时手动再创建一个application.yml文件,为了比较学习他们的区别(说明一下的就是,二者可以同时存在,不过最终只会运行一个,一般默认运行application.properties,不过我们可以通过配置,在application.properties中同时应用yml,达到多个配置文件的目的),依旧在resources目录下,直接右键new->File,创建一个名为application.yml的文件,如下图
在这里插入图片描述
YAML“YAML Ain’t a Markup Language”(YAML 不是一种标记语言)。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(是一种标记语言)。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件,即以数据为中心,比json、xml等更加适合做配置文件,以前的项目大都是使用xml作为配置文件的。

在全局配置文件中,可以对一些默认配置值进行修改,比如我们修改默认的端口号,我们如果使用xml作为配置文件,配置端口可能会是如下:

<server>
	<port>8081</port>
</server>

xml会浪费大量的内容给标签的开闭上,那如果我们在SpringBoot项目中使用properties和yml设置端口,又该如何呢,如下:

在这里插入图片描述
在这里插入图片描述

YAML语法

基本语法

  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • 大小写敏感

k:(空格)v:表示一对键值对(空格必须有);
空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的

数据类型

YAML 支持的三种数据结构:

  • 对象:键值对的集合
  • 数组:一组按次序排列的值
  • 字面量:单个的、不可再分的值

YAML常用写法

字面量:普通的值(数字,字符串,布尔)

k: v:字面直接来写;

  • 字符串默认不用加上单引号或者双引号;

  • "":双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思

name:   "zhangsan \n lisi":
输出;zhangsan 换行  lisi
  • '':单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name:   ‘zhangsan \n lisi’:
输出;zhangsan \n  lisi

对象、Map(属性和值)(键值对)

  • 对象的一组键值对,使用冒号分隔。如:username: admin
  • 冒号后面跟空格来分开键值;
  • {k: v}是行内写法(就是写在一行)
friends:
  lastName: zhangsan
  age: 20

行内写法:

friends: {
    
    lastName: zhangsan,age: 18}

数组(List、Set)

  • 一组连词线(-)开头的行,构成一个数组,[]为行内写法
  • 数组,对象可以组合使用
pets:
 - cat
 - dog
 - pig

行内写法

pets: [cat,dog,pig]

配置文件值注入案例

  • application.yml中写入一些数据,就是写一个类的属性值以及对应的数值,如下
person:
  lastNane: zhangsan
  age: 18
  boss: true
  birthday: 2021/01/01
  maps: {
    
    k1: v1,k2: v2}
  lists:
    - lisi
    - wangwu
    - zhaoliu
  dog:
    name: xiaohei
    age: 2
  • 创建一个Person类和一个Dog类,类中的属性值和配置文件中的属性值要一一对应,并在Person的类上加上@ConfigurationProperties注解,注解中的前缀填写我们在配置文件中的person,如下
/**
 * Dog类
 **/
@ConfigurationProperties(prefix = "person")
@Component
public class Person {
    
    

    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birthday;

    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;

	//以下是getter和setter、toString()方法,这里不在写出
	//直接ALT+INS快捷键生成就好

/**
 * Dog类
 **/
public class Dog {
    
    

    private String name;
    private Integer age;
//以下是getter和setter、toString()方法,这里不在写出
  • @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
  • prefix = "person":配置文件中哪个下面的所有属性进行一一映射
  • 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
  • @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
  • @Component,把类组件加到容器中
  • 要想使用@ConfigurationProperties这个注解,得要导入依赖:
<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
  • 编写测试类:
/**
 * SpringBoot单元测试;
 * 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能
 */
@SpringBootTest
class SpringbootConfigApplicationTests {
    
    

    @Autowired
    Person person;

    @Test
    void contextLoads() {
    
    
        System.out.println(person);
    }
}
  • 运行结果:
    在这里插入图片描述

使用properties完成案例

我们前面完成了使用yml类型的配置文件,进行映射注入,现在我们来试试使用application.properties类型的配置文件进行映射注入.我们先将yml配置文件中的内容注释掉(当然不注释也可以,因为默认是读取properties)。我们开始编写application.properties里面的内容,会发现我们在properties中编写的时候,已经有person的提示了,是因为我们已经建类组件注入容器了,现在我们在里面编写内容如下:

person.last-name=张三
person.age=18
person.boss=true
person.birthday=2021/01/01
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2
  • properties配置文件在idea中默认utf-8可能会乱码,解决方法如下:
    在这里插入图片描述
  • 运行结果:
    在这里插入图片描述

配置映射的另一种方式

上面我们进行了配置文件的编写,映射,注入以及如何进行测试相关的操作,在这里我们再来介绍另一种配置文件的映射注入,即使用其他注解的方式进行注入,我们这里要使用的注解是@Value@Value是Spring的底层注解。

  • 以前写SpringMvc的配置文件的时候,我们在配置文件中使用bean进行配置,然后进行相关映射:
<bean class="Person">
	<property name="lastName" value="字面量/环境变量/#{获取值}等等"></property>
<bean/>

以前的方式是我们通过一个一个给属性赋值,比如这里我们给lastName赋值,值就是value指定的。而@Value的作用其实和这里的value一样,相当于Spring帮我们简化了,只需要通过一个注解就能赋值,不过也是一个一个赋值

在这里插入图片描述

@ConfigurationProperties和@Value比较

我们上面使用的是@ConfigurationProperties映射yml或者properties配置文件,而在这里我们举例使用@Value进行配置,那么这两者有什么区别呢?如下表:

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

什么是松散语法呢?
比如我们有一个属性时lastName,我们在配置文件中的属性名和Person类中的属性名需要一致,不然没办法映射,但是在松散语法中,lastName和last-name是认为同一个,这种写法就是松散写法,也就是说,我们在配置文件中,person.lastNameperson.last-name两种写法都可以,但是@Value是不支持松散写法的,属性名必须一致


JSR30数据校验
就是校验器,比如对属性是否符合邮箱格式进行校验,不符合提示错误等,而配置文件注入值数据校验,只能使用ConfigurationProperties
在这里插入图片描述
要是提示没有这个注解的话,记得导入下面这个依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

那这两个属性我们什么时候用呢?

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

@PropertySource和@ImportResource

@PropertySource

  • 用来加载指定的配置文件

怎么理解呢?比如我们的application.propertiesapplication.yml是全局配置文件,我们原先把配置内容都是写到全局配置文件中的,然后我们使用@ConfigurationProperties或者@Value进行映射,也就是说@ConfigurationProperties或者@Value是默认映射全局配置文件的,那么如果项目一旦很大,我们不可能所有配置都写到全局配置文件中,所以这个时候我们需要创建一些其他的配置文件,然后指定映射。

  • 举个例子,在resources下面创建一个person.properties,然后把application.properties里面的内容粘贴到person.properties中,这个时候我们通过@PropertySource,将Person类和person.properties进行映射
    在这里插入图片描述

@ImportResource

  • @ImportResource是用来导入原先Spring的配置文件,让配置文件里面的内容生效,也就是说,如果想按照以前SpringMVC的那种出入配置,我们可以使用这个注解来完成。
  • 我们先在resourcs下创建一个bean.xml(就是以前Spring的配置文件),然后按照以前的方式写一个bean,如下内容
<?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.cz.service.HelloService"></bean>
</beans>
  • 在测试类中添加以下方法,使用ApplicationContext容器,判断容器中是否注入了helloService
@Autowired
    ApplicationContext ioc;

    @Test
    public void testHelloService(){
    
    
        boolean b = ioc.containsBean("helloService");
        System.out.println(b);
    }
  • 运行之后,控制台输出的是false,说明bean没有被注入容器
  • 这个时候就可以用到我们的@ImportResource了,SpringBoot里面没有Spring的配置文件,我们自己编写的Spring配置文件也不能自动识别,想让Spring的配置文件生效,加载进容器,就可以使用@ImportResource标注在一个配置类上,这里我们在主配置类上标注如下,再次运行测试类,结果就是true。
    在这里插入图片描述
  • 但是我们实际开发中不可能像这样使用注解一个一个导入,而我们SpringBoot推荐给容器中添加组件的方式,也就是使用纯注解的方式。如下:
  • 创建一个配置类
//指明当前类是一个配置类,替代之前的spring配置文件
@Configuration
public class MyConfig {
    
    

    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
    
    
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
}
  • 回到测试类,测试之前先把主配置类里面的@ImportResource去掉,我不使用@ImportResource注解,启动测试类,helloService注入依旧成功。

配置文件占位符

  • 随机数
    • RandomValuePropertySource:配置文件中可以使用随机数
${
    
    random.value}
${
    
    random.int}
${
    
    random.long}
${
    
    random.int(10)}
${
    
    random.int[1024,65536]}
  • 属性配置占位符
    • 可以在配置文件中引用前面配置过的属性(优先级前面配置过的这里都能用)。
    • ${app.name:默认值}来指定找不到属性时的默认值
      在这里插入图片描述

person.dog.name=${person.last-name}_dog,上面有last-name就是占位符
person.dog.name=${person.hello:hello}_dog,上面没有Hello。但是后面有默认值,运行之后,控制台会输出后面的默认值。如果没有默认值,直接当成一个字符输出。

Profile

profile是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境,通俗点理解就是,开发环境的配置,生产环境的配置,测试环境的配置分开,使用profile可以进行快速切换

切换方式(激活方式)

  • 命令行: --spring.profiles.active=dev (打包之后,使用命令行执行的时候,指定参数)
  • 配置文件:spring.profiles.active=dev
  • Jvm参数 -Dspring.profiles.active=dev (在Idea修改参数)

多profile文件形式

  • 首先我们创建三种配置(包括原来的application.properties在内的三个),一般的配置文件格式:application-{profile}.properties。比如application-dev.propertiesapplication-prod.properties。创建之后,我们可以在另外两个配置文件中配置我们想要的配置,现在我们就修改一下端口号,在主配置文件中进行激活即可,然后来看看控制台的输出结果。
    在这里插入图片描述
  • 最后在控制台输出的就是在 application-dev.properties中配置的端口号。

多profile文档块模式

上面是通过properties进行多profile的配置,我们也可以使用yml来进行多profile的配置,yml的配置更简洁,不需要额外创建像application-dev.propertiesapplication-prod.properties这样的配置文件,只需要在主yml配置文件中,使用“---”的文档块模式

server:
  port: 8081
spring:
  profiles:
    active: prod
---
server:
  port: 8083
spring:
  config:
    activate:
      on-profile: dev
---
server:
  port: 8085
spring:
  config:
    activate:
      on-profile: prod

配置文件加载位置

springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/

classpath是在resources目录位置,file是在项目根目录的位置,以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容,配置文件的内容是互补的,也就是说高优先级中没有的配置,如果低优先级有的话一样会生效,但是如果高优先级的配置中已经有了一项配置,低优先级中相同的配置就会被覆盖掉。

  • 我们也可以通过配置spring.config.location来改变默认配置,也就是说配置文件可以放在任意的位置,网络上或者电脑桌面任意位置,把位置路径赋给location就可以了。当我们项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置

外部配置的加载顺序

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

  1. 命令行参数

    • 所有的配置都可以在命令行上进行指定
    • java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
    • 多个配置用空格分开; --配置项=值
  2. 来自java:comp/env的JNDI属性

  3. Java系统属性(System.getProperties

  4. 操作系统环境变量

  5. RandomValuePropertySource配置的random.*属性值

由jar包外向jar包内进行寻找;优先加载带profile,再来加载不带profile

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

自动配置原理

在讲解入门案例的时候我们其实有提高过自动配置类,即@EnableAutoConfiguration,不过只是带过了他的作用,没有深入讨论,这里我们进行深入讨论,首先先放出所有自动配置文件属性的参考,官网文档位置

  • @EnableAutoConfiguration 的作用是利用AutoConfigurationImportSelector给容器中导入一些组件,详细的可以查看SpringFactoriesLoader.loadFactoryNames意思是扫描所有jar包类路径下,META-INF/spring.factories。把扫描到的这些文件的内容装成properties对象,然后从properties中获取到EnableAutoConfiguration.class类对应的值,然后把它们添加到容器中,
  • 也就是将类路径下META-INF/spring.factories里面配置的所有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.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
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.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
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.Neo4jReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
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.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
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.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
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.neo4j.Neo4jAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
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.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
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类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;每一个自动配置类进行自动配置功能;

  • 接下来我们以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;直接Ctrl+n搜索这个类
//表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@Configuration(
    proxyBeanMethods = false
)

//启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入到ioc容器中
@EnableConfigurationProperties({
    
    ServerProperties.class})

//Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;    判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnWebApplication(
    type = Type.SERVLET
)

//判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnClass({
    
    CharacterEncodingFilter.class})

//判断配置文件中是否存在某个配置  spring.http.encoding.enabled;如果不存在,判断也是成立的
//即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;
@ConditionalOnProperty(
    prefix = "server.servlet.encoding",
    value = {
    
    "enabled"},
    matchIfMissing = true
)

public class HttpEncodingAutoConfiguration {
    
    
	//他已经和SpringBoot的配置文件映射了
    private final Encoding properties;

	//只有一个有参构造器的情况下,参数的值就会从容器中拿
    public HttpEncodingAutoConfiguration(ServerProperties properties) {
    
    
        this.properties = properties.getServlet().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.web.servlet.server.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
        return filter;
    }

根据当前不同的条件判断,决定这个配置类是否生效?
一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的

  • 所有在配置文件中能配置的属性都是在xxxProperties类中封装这,配置文件能配置什么就可以参照某个功能对应的这个属性类,根据当前不同条件判断,决定这个配置是否生效。

  • 精髓

    • SpringBoot启动会加载大量的自动配置类
    • 我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;
    • 我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
    • 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这 些属性的值;
  • 总结一下自动配置文件的通用模式(即通过命名分辨)

    • xxxAutoConfiguration:自动配置类
    • xxxProperties:属性配置类。也就是说,我们yml/properties文件中能配置的值就来源于属性配置类

细节

  • @Conditional派生注解(Spring注解版原生的@Conditional作用)
  • 作用:
    • 必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;
@Conditional扩展注解 作用(判断是否满足当前指定条件)
@ConditionalOnJava 系统的java版本是否符合要求
@ConditionalOnBean 容器中存在指定Bean;
@ConditionalOnMissingBean 容器中不存在指定Bean;
@ConditionalOnExpression 满足SpEL表达式指定
@ConditionalOnClass 系统中有指定的类
@ConditionalOnMissingClass 系统中没有指定的类
@ConditionalOnSingleCandidate 容器中只有一个指定的Bean,或者这个Bean是首选Bean
@ConditionalOnProperty 系统中指定的属性是否有指定的值
@ConditionalOnResource 类路径下是否存在指定资源文件
@ConditionalOnWebApplication 当前是web环境
@ConditionalOnNotWebApplication 当前不是web环境
@ConditionalOnJndi JNDI存在指定项

自动配置类必须在一定的条件下才能生效,我们怎么知道哪些自动配置类生效;我们可以通过在配置文件中启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;
在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43844418/article/details/113939625
今日推荐