本文参考《Spring Boot实战》第4版第3.2章节通过属性文件外置配置。
Spring Boot版本:2.0.6.RELEASE。
源代码:https://github.com/wu-boy/parker.git,parker-config模块。
Spring Boot提供了一系列的默认配置,如果想自定义配置怎么办,这里给出了3种办法。
自动配置微调
常用的方法就是在application.yml中进行配置,覆盖默认的配置。
应用程序Bean的配置外置
在开发应用程序时,往往有很多可配置的参数,不能写死在程序里,因此需要配置文件来配置。这时可以通过提供一些配置类来读取配置文件中的参数,然后提供给应用程序使用。
使用Profile进行配置
当应用程序需要部署到不同的环境时,一些配置细节通常会有不同,比如开发环境、测试环境和生成环境等。Spring Boot支持基于Profile的配置。Profile是一种条件化配置,基于运行时激活的Profile,会使用或者忽略不同的Bean或配置类。
实例
本实例基于Parker项目进行扩展,新建parker-config模块,配置文件如下
application.yml
spring:
profiles:
active: dev
application-dev.yml
global-config:
name: dev
application-prod.yml
global-config:
name: prod
如果使用YAML来配置属性,可创建application-{profile}.yml这样的文件,并将与Profile无关的属性继续放在application.yml里。
新建配置类
package com.wu.parker.config.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author: wusq
* @date: 2019/1/10
*/
@Component
@ConfigurationProperties("global-config")
public class GlobalConfig {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
该配置类用于读取global-config中的name配置的值,加上@ConfigurationProperties注解,就可以收集配置属性了。
Spring Boot的属性解析器非常智能,它会自动把驼峰规则的属性和使用连字符“-”或下划线“_”的同名属性关联起来。
注意:Spring Boot的yml配置文件中 ,配置前缀0的数字时,会被特殊处理。
1、以0b开头的数字,会被当做二进制数处理
2、以0x开头的数字,会被当做十六进制数处理
3、以0开头的数字,会被当做八进制数处理
启动类
package com.wu.parker.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author: wusq
* @date: 2019/1/10
*/
@SpringBootApplication
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
测试类
package com.wu.parker.config.test;
import com.wu.parker.config.config.GlobalConfig;
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;
/**
* @author: wusq
* @date: 2019/1/10
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GlobalConfigTest {
@Autowired
private GlobalConfig globalConfig;
@Test
public void contextLoads() {
}
@Test
public void test() throws Exception {
System.out.println(globalConfig.getName());
}
}
修改application.yml中的active属性,可以加载不同的配置文件。
参考资料
1、《Spring Boot实战》第4版第3.2章节通过属性文件外置配置;
2、《spring boot 配置文件配置项前缀为0的数字特殊处理》,ChronosLiu著。