二、SpringBoot 配置篇


Spring Boot使用一个全局的配置文件,配置文件名是固定的

  • application.properties 或者
  • application.yml (使用 yaml 语法)

配置文件的作用

  • 修改 SpringBoot 自动配置的默认值。
  • SpringBoot 在底层都给我们自动配置好。

一、yaml 简介

1-1、YAML(YAML Ain't Markup Language):
  • YAML A Markup Language:是一个标记语言。
  • YAML isn't Markup Language:不是一个标记语言。
1-2、标记语言
  • 以前的配置文件;大多都使用的是 xxxx.xml文件。
  • YAML:以数据为中心,比 json、xml 等更适合做配置文件。
  • YAML 配置实例与 xml 配置对比。

yaml:

server:
  port: 8081

xml:

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

二、yaml 语法

2-1、基本语法
  • 使用缩进表示层级关系。空格个数代表缩进层级。
  • 缩进时不允许使用 Tab 键,只允许使用空格。
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可。
  • 大小写敏感。
  • YAML 支持三种数据结构
    • 对象:键值对的集合。
    • 数组:一组按次序排列的值。
    • 字面量:单个的、不可再分的值。
2-2、值的写法(三种数据结构)
  • 对象(键值对)

对象的一组键值对,使用冒号分隔。如:username: admin 冒号后面跟空格来分开键值。

{k: v}是行内写法

person:
 name: xiaoming
 sex: man
 brithdate: 2018/11/5
 age: 12

person: {name: xiaoming,sex: man,birthdate: 2018/11/5,age: 12} #行内写法
  • 数组(List、Set)
pets:
 - cat1
 - dog1
 - pig1

#pets: [cat2,dog2,pig2] #行内写法
  • 字面量

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

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

'':单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据。

name:   ‘zhangsan 
 lisi’ # 输出:zhangsan 
  lisi

总结
YML是一种新式的格式,层级鲜明,个人比较喜欢使用的一种格式,注意如下:

    1. 字符串可以不加引号,若加双引号则输出特殊字符,若不加或加单
      引号则转义特殊字符。
    1. 数组类型,短横线后面要有空格;对象类型,冒号后面要有空格。
    1. YAML 是以空格缩进的程度来控制层级关系,但不能用 tab 键代替空格,大小写敏感

三、如何从 yaml 配置文件获取值?

3.1、使用 @configurationProperties、@Value 取值

1、@configurationProperties:告诉 SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定, prefix = "person":配置文件中哪个下面的所有属性进行一一映射。

配置文件:application.yaml

# 1、测试 Yaml 语法 对象、Map(属性和值)(键值对)如何书写
  # 对象中含有引用类型对象属性时如何书写?
person:
 name: xiaoming
 sex: man
 brithdate: 2018/11/5
 age: 12

#person: {name: xiaoming,sex: man,birthdate: 2018/11/5,age: 12} #行内写法

Java beans

/**
 * 需求:将配置文件中配置的每一个属性的值,映射到这个 Person 类组件中。
 * @ConfigurationProperties:告诉 SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定;
 * prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能使用容器提供的 @ConfigurationProperties 功能;
 *
 */
@ConfigurationProperties(prefix = "person")
@Component//注入到IOC容器中
public class Person {
    String name;
    String sex;
    Integer age;
    Date brithdate;

    public Person(){

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBrithdate() {
        return brithdate;
    }

    public void setBrithdate(Date brithdate) {
        this.brithdate = brithdate;
    }

    @Override
    public String toString() {
        return "Person[name:"+name+",sex:"+sex+",age:"+age+",brithdate:"+brithdate+"]";
    }
}

2、@Value
@Value 这个注解估计很熟悉了,Spring中从属性取值的注解,支持 SPEL 表达式,不支持复杂的数据类型,比如 List 。使用如下:

@Value("${userinfo.name}")
private String UserName;
3-2、Spring boot 的单元测试 @SpringBootTest
/**
 * 需求:如何进行 SpringBoot 单元测试。
 * 使用 @RunWith(SpringRunner.class)、 @SpringBootTest 两个注解。
 * 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能。
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ConfigApplicationTests {

    @Autowired
    ApplicationContext ioc;

    /*************************测试配置文件值注入*******************************/
    /**
     * 1、测试 @ConfigurationProperties 注解
     */
    @Test
    public void testConfigurationProperties(){
       Person p= (Person) ioc.getBean("person");
       System.out.println(p);
    }

}

四、如何从 properties 配置文件取值?

properties 配置文件格式简介及取值

常见的一种配置文件格式,Spring中也是用这种格式,语法结构很简单,结构为: key=value 。具体如下:

userinfo.name=myjszl
userinfo.age=25
userinfo.active=true
userinfo.created-date=2018/03/31 16:54:30
userinfo.map.k1=v1
userinfo.map.k2=v2

对应的实体类:
@Data
@ToString
public class UserInfo {
private String name;
private Integer age;
private Boolean active;
private Map<String,Object> map;
private Date createdDate;
private List<String> hobbies;
}
properties 配置文件编码问题:在该菜单可修改项目的全局编码


images/1542252013950.png


五、@configurationProperties 与 @Value 区别

5.1、@Value 获取值和 @ConfigurationProperties 获取值比较

配置文件是 yml 还是 properties 他们都能获取到值。

如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value(直接使用在 bean 的成员属性上)。

如果说,我们专门编写了一个 javaBean 来和配置文件进行映射,我们就直接使用。

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

#{} 为 SpEL 表达式
${} 为 EL 表达式。
使用 @Validated 注解进行数据的校验。

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     * <property name="lastName" value="字面量 ${key} 从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

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

六、如何从自定义配置文件中取值?

  • @PropertySource:从自定义配置文中取值
  • @ImportResource:导入 Spring 的配置文件,让配置文件里面的内容生效。
  • @Bean : 将返回的结果注入到 IOC 容器中。
6.1、从自定义配置文件中取值 @PropertySource。

1、Spring Boot在启动的时候会自动加载 application.xxxbootsrap.xxx ,但是为了区分,有时候需要自定义一个配置文件,那么如何从自定义的配置文件中取值呢?此时就需要配合 @PropertySource 这个注解使用了。
只需要在配置类上标注 @PropertySource 并指定你自定义的配置文件即可完成,如下:

/**
 * 需求:将配置文件中配置的每一个属性的值,映射到 Person 类这个组件中
 * @ConfigurationProperties:告诉 SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定;
 *  prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的 @ConfigurationProperties 功能;
 *  @ConfigurationProperties(prefix = "person") 默认从全局配置文件中获取值;
 *  @PropertySource 注解指定从哪个配置文件加载配置属性。
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

2、如何加载自定义YML格式的配置文件?

@PropertySource 注解有一个属性 factory ,默认值是 PropertySourceFactory.class ,这个就是用来加载 properties 格式的配置文件,我们可以自定义一个用来加载 YML 格式的配置文件。

package com.pengguozhen.springboot02config.utils;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.util.Properties;

import java.io.IOException;
import java.util.Properties;

public class YmlConfigFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name,
                                                  EncodedResource resource) throws IOException {
        String sourceName = name != null ? name :
                resource.getResource().getFilename();
        if (!resource.getResource().exists()) {
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") ||
                sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName,
                    propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws
            IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}

此时只需要将 factory 属性指定为 YmlConfigFactory 即可,如下:

@SpringBootApplication
@PropertySource(value = {"classpath:custom.yml"},factory =
YmlConfigFactory.class)
public class DemoApplication {
}

总结:@PropertySource 指定加载自定义的配置文件,默认只能加载 properties 格式,但是可以指定 factory 属性来加载 YML 格式的配置文件。

6.2、SpringBoot 推荐给容器中添加组件的方式

1、@ImportResource:导入 Spring的配置文件,让配置文件里面的内容生效;
2、@Bean 注册类实例到容器。

需求:Spring Boot 里面没有 Spring 的配置文件,我们自己编写的配置文件,也不能自动识别,想让 Spring 的配置文件生效,加载进来;@ImportResource 标注在一个配置类上。

方法一:

@ImportResource(locations = {"classpath:beans.xml"})
导入 Spring 的配置文件让其生效 。

beans.xml

<?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.atguigu.springboot.service.HelloService"></bean>
</beans>

方法二:

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

1、配置类 @Configuration------>Spring 配置文件

2、使用 @Bean 给容器中添加组件

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的 Spring 配置文件
 *
 *  使用 @Bean 注解将类实例注册到容器中
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中;容器中这个组件默认的 id 就是方法名。
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类使用 @Bean 注解给容器中添加组件了...");
        return new HelloService();
    }
}

七、配置文件占位符

  • 随机数。
${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}
  • 占位符获取之前配置的值,如果没有可以是用:指定默认值。
person.last-name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=15

八、Profile 多环境支持(测试、开发、生产环境)

8.1、多 Profile 文件

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

默认使用 application.properties的配置。

  • yml 支持多文档块方式。

server:
 port: 8081
spring:
 profiles:
   active: prod

---
server:
 port: 8083
spring:
 profiles: dev

---

server:
 port: 8084
spring:
 profiles: prod  #指定属于哪个环境
8.1、激活指定 profile。
1、在配置文件中指定  spring.profiles.active=dev

2、命令行:

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;

可以直接在测试的时候,配置传入命令行参数

3、虚拟机参数;

-Dspring.profiles.active=dev

九、配置文件的加载位置

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

–file:./config/

–file:./

–classpath:/config/

–classpath:/

优先级由高到底,高优先级的配置会覆盖低优先级的配置;

SpringBoot 会从这四个位置全部加载主配置文件;互补配置;

==我们还可以通过 spring.config.location 来改变默认的配置文件位置==

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

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=G:/application.properties

十、外部配置加载顺序

==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 ==

6.jar 包外部的 application-{profile}.properties 或 application.yml (带spring.profile)配置文件

7.jar 包内部的 application-{profile}.properties或application.yml(带spring.profile)配置文件

==再来加载不带 profile ==

8.jar包外部的application.properties或application.yml(不带spring.profile)配置文件

9.jar包内部的application.properties或application.yml(不带spring.profile)配置文件

10.@Configuration 注解类上的@PropertySource

11.通过SpringApplication.setDefaultProperties指定的默认属性

所有支持的配置加载来源;

十一、自动配置原理。重点

1、SpringBoot 启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration。

通过 @SpringBootApplication 注解(应用程序入口)
-->执行 @EnableAutoConfiguration
-->执行 @Import({AutoConfigurationImportSelector.class}

2、@EnableAutoConfiguration 作用
  • 利用 AutoConfigurationImportSelector 给容器中导入一些组件(可以查看selectImports()方法的内容)。
  • getAutoConfigurationEntry()
  • List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置。
SpringFactoriesLoader.loadFactoryNames()
扫描所有jar 包类路径下  META-INF/spring.factories
把扫描到的这些文件的内容包装成 properties 对象
从 properties 中获取到 EnableAutoConfiguration.class 类(类名)对应的值,然后把他们添加在容器中。

将类路径下 META-INF/spring.factories 里面配置的所有 EnableAutoConfiguration 的值加入到了容器中;

# 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.CloudAutoConfiguration,
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.CassandraRepositoriesAutoConfiguration,
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,
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.jpa.JpaRepositoriesAutoConfiguration,
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,
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.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.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.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.flyway.FlywayAutoConfiguration,
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,
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.mobile.DeviceResolverAutoConfiguration,
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,
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.DispatcherServletAutoConfiguration,
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

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

3、以 HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理。
@Configuration   
//表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
 
@EnableConfigurationProperties(HttpEncodingProperties.class) 
//启动指定类的 ConfigurationProperties 功能;将配置文件中对应的值和 HttpEncodingProperties 绑定起来;并把 HttpEncodingProperties 加入到 ioc 容器中

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

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

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

public class HttpEncodingAutoConfiguration {

  	//他已经和SpringBoot的配置文件映射了
  	private final HttpEncodingProperties properties;

   //只有一个有参构造器的情况下,参数的值就会从容器中拿
  	public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
        this.properties = properties;
    }

    @Bean   
	//给容器中添加一个组件,这个组件的某些值需要从 properties 中获取
    @ConditionalOnMissingBean(CharacterEncodingFilter.class) 
	//判断容器没有这个组件?
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
        return filter;
    }

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

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

4、所有在配置文件中能配置的属性都是在 xxxxProperties 类中封装者‘;配置文件能配置什么就可以参照某个功能对应的这个属性类。
@ConfigurationProperties(prefix = "spring.http.encoding")  
//从配置文件中获取指定的值和bean的属性进行绑定
public class HttpEncodingProperties {

   public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

精髓:

 	1)、SpringBoot 启动会加载大量的自动配置类。

 	2)、我们看需要的功能有没有 SpringBoot 默认写好的自动配置类;

 	3)、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)。

 	4)、给容器中自动配置类添加组件的时候,会从 properties 类中获取某些属性。我们就可以在配置文件中指定这些属性的值;

xxxxAutoConfigurartion:自动配置类;

给容器中添加组件

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


十二、@Conditional & 自动配置报告

细节

12.1、@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存在指定项 

自动配置类必须在一定的条件下才能生效;

12.2、我们怎么知道哪些自动配置类生效(自动配置报告)

我们可以通过在属性配置文件启用 debug=true 属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;

  =========================
    AUTO-CONFIGURATION REPORT
    =========================

    Positive matches:(自动配置类启用的)
    -----------------

       DispatcherServletAutoConfiguration matched:
          - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
          - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)

    Negative matches:(没有启动,没有匹配成功的自动配置类)
    -----------------

       ActiveMQAutoConfiguration:
          Did not match:
             - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

       AopAutoConfiguration:
          Did not match:
             - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice' (OnClassCondition)

原文地址:https://www.cnblogs.com/pengguozhen/p/14082752.html