想要覆盖Spring Boot的自动配置,我们所要做的仅仅是编写一个显式的配置。
Spring Boot会发现我们的配置,随后降低自动配置的优先级,以我们的配置为准。想弄明白这是如何实现的,让我们揭开Spring Boot自动配置的神秘面纱,看看它是如何运作的,以及它是怎么允许自己被覆盖的。

Spring Boot自动配置自带了很多配置类,每一个都能运用在我们的应用程序里。它们都使用了Spring 4.0的条件化配置,可以在运行时判断这个配置是该被运用,还是该被忽略。

Spring Boot自动配置的Bean提供了300多个用于微调的属性。当我们调整设置时,只要在环境变量、Java系统属性、JNDI(Java Naming and Directory Interface)、命令行参数或者属性文件里进行指定就好了。

Spring Boot应用程序有多种设置途径。Spring Boot能从多种属性源获得属性,包括如下几处。

(1) 命令行参数
(2) java:comp/env 里的JNDI属性
(3) JVM系统属性
(4) 操作系统环境变量
(5) 随机生成的带 random.* 前缀的属性(在设置其他属性时,可以引用它们,比如 ${random.
long} )
(6) 应用程序以外的application.properties或者appliaction.yml文件
(7) 打包在应用程序内的application.properties或者appliaction.yml文件
(8) 通过 @PropertySource 标注的属性源
(9) 默认属性

这个列表按照优先级排序,也就是说,任何在高优先级属性源里设置的属性都会覆盖低优先级的相同属性。例如,命令行参数会覆盖其他属性源里的属性。

application.properties和application.yml文件能放在以下四个位置。
(1) 外置,在相对于应用程序运行目录的/config子目录里。
(2) 外置,在应用程序运行的目录里。
(3) 内置,在config包内。
(4) 内置,在Classpath根目录。
同样,这个列表按照优先级排序。也就是说,/config子目录里的application.properties会覆盖应用程序Classpath里的application.properties中的相同属性。
此外,如果我们在同一优先级位置同时有application.properties和application.yml,那么application.yml里的属性会覆盖application.properties里的属性。

读取属性

读取application.yml中的localhost配置的值

package com.gwc.context;

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

/**
 * Created by gwcheng on 2017/3/6.
 */
@Component
@ConfigurationProperties
public class SystemProperties
{
    private String localhost;

    public String getLocalhost() {
        return localhost;
    }

    public void setLocalhost(String localhost) {
        this.localhost = localhost;
    }
}

还可以在Bean中使用

@Value("${server.port}")
private String serverPort;

来读取配置文件中的属性值

使用 Profile 进行配置

当应用程序需要部署到不同的运行环境时,一些配置细节通常会有所不同。比如,数据库连接的细节在开发环境下和测试环境下就会不一样,在生产环境下又不一样。Spring Framework从Spring 3.1开始支持基于Profile的配置。Profile是一种条件化配置,基于运行时激活的Profile,会使用或者忽略不同的Bean或配置类。

使用YAML来配置属性,则可以遵循与配置文件相同的命名规范,即创建application-{profile}.yml这样的YAML文件,并将与Profile无关的属性继续放在application.yml里。

这里我们配置三个配置文件

springboot StringRedisTemplate自定义 springboot自定义enable_优先级

application.yml里面的配置

localhost: gwchsk.imwork.net
spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/bootdb
    username: root
    password: cheng
  jpa:
    hibernate:
      ddl-auto: update

application-dev.yml里面的配置如下

server:
  port: 8080
  context-path: /springboot
spring:
  thymeleaf:
    cache: false

application-prod.yml的配置如下

server:
  port: 80
  context-path: /springboot
spring:
  thymeleaf:
    cache: true

其中application.yml里的spring.profiles.active:dev表示激活application-dev.yml

当运行springboot的时候就是8080端口并关闭thymeleaf缓存

如果application.yml里的spring.profiles.active:prod则运行springboot的时候就是80端口启用thymeleaf缓存

github已同步

https://github.com/peer44/springboot

参考文献

Walls C. Spring Boot in Action[J]. 2016.