SpringBoot(二)配置

本次创建新的工程,pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springboot.config</groupId>
    <artifactId>spring-boot-02-config</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <!--导入配置文件处理器,配置文件进行绑定就会有提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

注意:parent工程是 spring-boot-starter-parent ,而不是 spring-boot-parent ,不要把starter漏掉了

1、SpringBoot的配置文件简介 

       SpringBoot引入了大量的自动配置,同时也支持自定义配置,SpringBoot使用一个全局的配置文件,配置文件名是固定的;
application.propertiesapplication.yml

       yml是YAML(YAML Ain't Markup Language),YAML A Markup Language:是一个标记语言,YAML isn't Markup Language:不是一个标记语言;

       标记语言:以前的配置文件;大多都使用的是 xxxx.xml文件;
       YAML:以数据为中心,比json、xml等更适合做配置文件;
YAML:配置例子

server:
  port: 8081

经过上面的配置之后,SpringBoot的项目会由默认配置的8080,变成现在配置的8081。 

XML:

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

2、YML语法

2.1 基本语法

k:(空格)v:表示一对键值对(空格必须有);
       以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的,属性和值也是大小写敏感

server:
  port: 8088
  context-path: /config

注意:context-path是配置项目的上下文,一定要以 / 开头,不能以 / 结尾,否则会报错:

Initialization of bean failed; nested exception is java.lang.IllegalArgumentException:ContextPath 
must start with '/' and not end with '/'

2.2 值的写法

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

k: v:字面直接来写;
       字符串默认不用加上单引号或者双引号;如果加,双引号和单引号会有不同的意思:
              "":双引号;不会转义字符串里面的特殊字符;特殊字符会作为本身想表示的意思
                           name: "zhangsan \n lisi":输出;zhangsan 会有换行效果 lisi
              '':单引号;会转义特殊字符,特殊字符最终只是一个普通的字符串数据
                           name: ‘zhangsan \n lisi’:输出;zhangsan \n lisi

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

k: v:在下一行来写对象的属性和值的关系;注意缩进,对象还是k: v的方式

person:
  last-name: "张三 \n 你好"
  addr: '湖南 \n 长沙'

还有一种行内写法:

dog: {name: 小狗, color: black}

2.2.3 数组(List、Set)

- 值表示数组中的一个元素:

color:
  - blue
  - black
  - green

行内写法:

brands: [audi,baoma,benchi]

2.3 配置文件值注入@ComfigurationProperties

2.3.1 创建两个JavaBean

package com.springboot.config.bean;

public class Car {
    private String brand;
    private String color;
    //get/set和toString方法
}
package com.springboot.config.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "user":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
*
*/
@Component
@ConfigurationProperties(prefix = "user")
public class User {
    private String lastName;
    private int age;
    private Date birthday;
    private boolean teacher;
    private Map pets;
    private List<String> friends;
    private Car car;
    //get/set和toString方法
}

       特别注意:改注解上方有两个注解:@Component:注册组件到Spring的IOC容器中;@ComfigurationProperties(prefix = "user"):该注解是从配置文件中把和User类中的属性名对应的配置值设置到user对象中,并且是找配置文件中前缀是user开头的。 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;所以需要加上@Component注解,注册组件到IOC容器中。

2.3.2 创建配置文件application.yaml

为了写配置文件的时候有提示,可以在pom.xml中导入下面的坐标:

<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

application.yml内容如下: 

server:
  port: 8088
  context-path: /config
user:
  last-name: 张三
  age: 23
  birthday: 1997/12/12
  teacher: true
  pets: {cat: tom,dog: jack}
  friends:
    - 李四
    - 王五
  car:
    brand: audi
    color: black

2.3.3 测试

       SpringBoot的单元测试有一个专门的starter需要引入,通过对应的注解就可以实现单元测试,并且在测试类中也可以使用@Autowired注解从IOC容器中获取对应的组件:

在pom.xml中引入:

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

在src/test/java下面创建测试包,包下创建测试类:

package com.springboot.config.test;

import com.springboot.config.bean.User;
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;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ConfigApplicationTest {

    @Autowired
    private User user;
    @Test
    public void test(){
        System.out.println(user);
    }

}

可以在测试期间很方便的类似编码一样进行自动注入等容器的功能

运行测试方法,打印结果:

User{lastName='李四', age=33, birthday=Sat Sep 01 00:00:00 CDT 1990, teacher=true,
pets={dog=jack, cat=tom}, friends=[张三, 王五], car=Car{brand='Audi', color='black'}}

2.3.4 如果使用的是properties配置文件呢

注意,如果使用application.properties文件,中文配置可能为乱码,需要进行如下的设置:

然后可以把application.yml中的内容注释,application.properties的配置如下:

server.port=8088
server.context-path=/config

user.last-name=李四
user.age=33
user.birthday=1990/09/01
user.teacher=true
user.pets.cat=tom
user.pets.dog=jack
user.friends=张三,王五
user.car.brand=Audi
user.car.color=black

打印结果:

User{lastName='李四', age=33, birthday=Sat Sep 01 00:00:00 CDT 1990, teacher=true, 
pets={dog=jack, cat=tom}, friends=[张三, 王五], car=Car{brand='Audi', color='black'}}

2.4 @Value从配置文件中单个值注入到JavaBean属性中

       上面 2.3 是通过注解 @ConfigurationProperties 给JavaBean的整个对象注入值,当然也可以通过@Value注解来进行单个值的注入。

package com.springboot.config.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @RestController注解其实在 @ResponseBody和@Controller的组合注解
 * 它表示该类所有方法的返回值都会封装成json返回
 */
@RestController
public class ConfigController {

    @Value("${user.last-name}")
    private String lastName;
    @Value("${user.age}")
    private int age;

    @RequestMapping("/config")
    public String config(){
        System.out.println("名字:"+lastName+"---年龄:"+age);
        return "application.yml和application.properties两种配置文件都可以,名字是固定的,用来修改自动配置的值";
    }
}

通过@Value注解,可以把配置文件中user.last-name和user.age的值注入给lastName和age

2.5 @Value获取值和@ConfigurationProperties获取值比较

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

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

2.6 配置文件注入值数据校验

@Validate 放在JavaBean类上,用来做数据校验,在属性上使用对应的注解进行相关的校验操作,比如@Email:

import org.hibernate.validator.constraints.Email;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@ConfigurationProperties(prefix = "user")
@Validated
public class User {
    @Email
    private String lastName;

此时如果启动项目,从配置文件取出user.lastName的值不是邮箱格式的话,就会报错:

Binding to target User{lastName='李四', age=33, birthday=Sat Sep 01 00:00:00 CDT 1990, teacher=true, 
pets={dog=jack, cat=tom}, friends=[张三, 王五], car=Car{brand='Audi', color='black'}} failed:

    Property: user.lastName
    Value: 李四
    Reason: 不是一个合法的电子邮件地址

2.7 @PropertySource&@ImportResource&@Bean

2.7.1 @PropertySource(只能用于properties文件)

       我们已经用注解 @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
prefix = "user":配置文件中哪个下面的所有属性进行一一映射,它是默认从 全局配置文件 (application.properties或application.yml)中获取值;

       但是如果都写到全局配置文件,东西太多会很乱,像上面这种配置完全可以提取出来,放到一个单独的配置文件中,比如我们在resources下面新建一个user.properties配置文件:

user.last-name=李四
user.age=33
user.birthday=1990/09/01
user.teacher=true
user.pets.cat=tom
user.pets.dog=jack
user.friends=张三,王五
user.car.brand=Audi
user.car.color=black

然后在JavaBean的User类上加上注解@PropertySource("classpath:user.properties"),也可以把配置文件的值映射进来。

@Component
@ConfigurationProperties(prefix = "user")
@PropertySource("classpath:user.properties")
public class User {

2.7.2 @ImportResource

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

      Spring Boot里面没有Spring的配置文件(applicationContext.xml),我们自己编写的配置文件,也不能自动识别;想让Spring的配置文件生效,加载进来;可以把注解 @ImportResource 标注在一个配置类上

比如我们在resources下面,创建xml/applicationContext.xml配置文件,在里面配置一个<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.springboot.config.service.HelloService"></bean>
</beans>

当然,我们应该在com.springboot.config.service包下已经创建了类:HelloService。

可以在著配置类上添加注解:@ImportResource("classpath:xml/applicationContext.xml")

package com.springboot.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:xml/applicationContext.xml")
public class ConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class,args);
    }
}

测试是否可以从IOC容器中获取到HelloService:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ConfigApplicationTest {
    @Autowired
    private ApplicationContext applicationContext;

    @Test
    public void testIoc(){
        HelloService helloService = (HelloService) applicationContext.getBean("helloService");
        System.out.println(helloService);
        //com.springboot.config.service.HelloService@6ef7623
    }
}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------        不过,SpringBoot推荐给容器中添加组件的方式:使用全注解的方式,配置类上加上注解@Configuration,同时使用@Bean注解来注入组件:

package com.springboot.config.conf;

import com.springboot.config.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MySpringConfig {

    @Bean//将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    public HelloService helloService(){
        return new HelloService();
    }
}

此时,我们可以注释掉配置类上的@ImportResource:

//@ImportResource("classpath:xml/applicationContext.xml")
public class ConfigApplication {

运行测试类,照样可以从IOC容器中获取到HelloService。

3、配置文件占位符

3.1 随机数

在配置文件中,可以使用${random}

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

3.2 占位符获取之前配置的值,如果没有可以使用:指定默认值

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

4、profile

4.1 多Profile文件

4.1.1 properties文件

我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml
默认使用名称为:application.properties的配置文件,可以在application.properties中使用 配置项 spring.profiles.active=dev 指定使application-dev.properties 生效:

application.properties

server.port=8088
server.context-path=/config
spring.profiles.active=dev

application-dev.properties 内容如下:

server.port=8082
server.context-path=/config2

此时,启动项目的端口会是8082,上下文也是/config2,而不是application.properties中配置的8088和config。

4.1.2 yml配置文件

       上面是演示的properties文件,可以创建多个,然后在默认的application.propeties中使用spring.profiles.active来指定激活哪个配置文件。如果是使用yml配置文件的话,可以不创建多个yml,也能达到效果。

       在yml文件中,使用  ---(三个短横杠)来给文件分割成多个Document,也可以使用spring.profiles.active来指定激活的Document,使用 spring: profiles: dev  #指定属于哪个环境

server:
  port: 8089
  context-path: /config8
spring:
  profiles:
    active: dev
---
server:
  port: 9000
  context-path: /dev
spring:
  profiles: dev
---
server:
  port: 9001
  context-path: /prod
spring:
  profiles: prod
---
server:
  port: 9002
  context-path: /test

spring:
  profiles: test

4.2 激活指定profile

上面我们已经在配置文件中使用spring.profiles.active来激活指定的profile,其实这不是唯一的方式,一共有三种方式激活profile:

1、在配置文件中使用 spring.profiles.active=dev  (注意:是 profiles 不是profile,s不能丢掉了)

2、在项目打包之后,使用 java -jar xxx.jar --spring.profiles.active=dev  命令行参数 也能激活指定的profile。多个命令行参数使用空格分开,以 --(两横杠)开头。在IDEA中,也可以配置命令行参数,

3、还可以配置虚拟机参数,-Dspring.profiles.active=dev 也可激活profile(-D 是虚拟机参数的固定写法,多个参数也是空格分开)。在IDEA中可以配置命令行参数和虚拟机参数,选择 Edit Configurations:

5、配置文件加载位置

springboot 启动会扫描以下位置的 application.properties或者application.yml 文件作为Spring boot的默认配置文件
       –file:./config/      ——也就是项目根目录下面的config目录
       –file:./                 ——项目根目录
       –classpath:/config/      ——类路径下的config目录(也就是resources下面的config目录)
       –classpath:/        ——类路径下,也就是resources下面
优先级由高到底,高优先级的配置会覆盖低优先级的配置;

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

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

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

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

       这就相当于我们的项目打包之后,使用java -jar 命令执行的是,可以使用命令行参数 --spring.config.location来指定盘符下的某个配置文件,这样对于运维来说是大有好处的。如果我们项目已经打包,但是需要修改某一些配置的时候,我们可以创建一个配置文件,启动项目的时候就可以执行配置文件的位置。

6、外部配置加载顺序

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

1、命令行参数

所有的配置都可以在命令行上进行指定,如果参数过多,就可以使用--spring.config.location来指定一个配置文件,

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指定的默认属性

所有支持的配置加载来源:参考官方文档

7、自动配置原理

我们要搞明白:配置文件到底能写什么?怎么写?那就算搞懂了自动配置原理;
配置文件能配置的属性参照:1.5.9官方文档的自动配置项       2.2.6官方文档的自动配置项

7.1 跟源码查看自动配置原理

1、SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration(主配置类的@SpringBootApplication 注解上面标注有@EnableAutoConfiguration)

2、@EnableAutoConfiguration 作用

@AutoConfigurationPackage
@Import({EnableAutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

@AutoConfigurationPackage 这个注解是用来配置自动配置的包的,默认是扫描主配置类及其子包;

@Import({EnableAutoConfigurationImportSelector.class}) 用来给容器导入一些组件的,可以查看 EnableAutoConfigurationImportSelector的父类的AutoConfigurationImportSelector里面的selectImports()方法的内容;

List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置 

进入该方法查看:

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():扫描所有jar包类路径下 META‐INF/spring.factories,把扫描到的这些文件的内容包装成properties对象,从properties中获取到 EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中

在我们导入的 spring-boot-autoconfigure:1.5.9.RELEASE.jar 包的 类路径下的 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、每一个自动配置类进行自动配置功能;

4、以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;

package org.springframework.boot.autoconfigure.web;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.HttpEncodingProperties.Type;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.filter.OrderedCharacterEncodingFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.filter.CharacterEncodingFilter;

@Configuration
@EnableConfigurationProperties({HttpEncodingProperties.class})
@ConditionalOnWebApplication
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = 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;
    }
}

@Configuration :表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件

@EnableConfigurationProperties(HttpEncodingProperties.class) :启动指定类(HttpEncodingProperties)的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,也是默认生效的;

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

5、所有在配置文件中能配置的属性都是在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:封装配置文件中相关属性;

7.2 细节

7.2.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环境
@ConditionalOnJndiJNDI存在指定项

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

我们怎么知道哪些自动配置类生效?我们可以通过在application.properties配置文件中 启用 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)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:
      - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
//。。。下面还有很多


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)

//。。。。下面还有很多

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值