前言
使用过Spring Boot的小伙伴都知道,他的配置参数必不可少,比如MySql的连接,端口号的配置等等,都需要Spring Boot的config参数配置,下面我们就来认识一下,我们工作开发中,常用的一些配置,以及获取配置参数的方式。
一、两种配置文件
首先我们知道SpringBoot中有以下两种配置文件bootstrap (.yml 或者 .properties),application (.yml 或者 .properties),那么他们各有什么区别呢?
1、加载顺序上的区别
bootstrap.yml(bootstrap.properties)先加载,application.yml(application.properties)后加载。
2、应用场景
2.1 bootstrap.yml 和application.yml 都可以用来配置参数。
2.2 bootstrap.yml 可以理解成系统级别的一些参数配置,这些参数一般是不会变动的。
2.3 applicationn.yml 可以用来定义应用级别的,主要用于 Spring Boot 项目的自动化配置。
bootstrap 配置文件有以下几个应用场景。
使用 Spring Cloud Config 配置中心时,这时需要在 bootstrap 配置文件中添加连接到配置中心的配置属性来加载外部配置中心的配置信息; 一些固定的不能被覆盖的属性 一些加密/解密的场景;
二、不同环境配置文件
在工作中,经常会遇到很多不同的环境,比如开发用的本地数据库,线上用的另一套数据库,线上环境用的又是另一套数据库,每次改端口,特别繁琐,怎么办呢?根据不同的环境,配置不同的文件即可。
spring.profiles.active 通过该属性来指定哪些配置文件处于活动状态。
 切换不同的环境,使用不同的端口号: 
三、读取配置文件信息
1、@Value注解读取文件
比如我们定义两个参数:name = DT辰白 age=24
 通过@Value注解读取参数,这里@Configuration中也可以写成@Component ,从定义来看,@Configuration注解本质上还是@Component,后面会有文章讲解关于这两个主键的区别。
@Configuration
public class ConfigParamsConfiguration {
@Value("${dt.name}")
private String name;
@Value("${dt.age}")
private Integer age;
public String getConfig() {
return name+"/"+age;
}
}
接口测试:
@RestController
@RequestMapping("api/test")
public class ConfigController {
@Autowired
private ConfigParamsConfiguration configParamsConfiguration;
@GetMapping("/getParams")
public String getConfig(){
return configParamsConfiguration.getConfig();
}
}

2、Environment读取文件
新建config.yml文件,配置和上面一样的内容:
 通过Environment实例读取config.yml文件里面的内容:
@Configuration
@PropertySource(value = {"classpath:config.yml"})
public class EnvironmentParamsConfiguration {
@Autowired
private Environment environment;
public String getConfig(){
String name = environment.getProperty("dt.name");
String age = environment.getProperty("dt.age");
return name+"/"+age;
}
}
@PropertySource(value = {"classpath:config.yml"})
测试:
@Autowired
private EnvironmentParamsConfiguration environmentParamsConfiguration;
@GetMapping("/getEnvParams")
public String getEnvParams(){
return environmentParamsConfiguration.getConfig();
}

3、@ConfigurationProperties读取配置文件
在有大量参数的时候,一个个添加 @Value 就显得麻烦了一点,Spring 提供了另一种方式。

oauth:
clientId: qq_41107231
clientSecret: secret
redirectUri: https://blog.csdn.net/qq_41107231
grantType: code
通过@ConfigurationProperties实例读取文件里面的内容:
@Data
@Component
@ConfigurationProperties(prefix = "oauth")
public class ConfigurationPropertiesParamsConfiguration {
private String clientId;
private String clientSecret;
private String redirectUri;
private String grantType;
}
1、@ConfigurationProperties 可以添加前缀,然后其属性就会按照变量的名称默认在 application.* 中寻找指定的变量。 2、必须要加@Data,因为这样可以自动的帮助添加默认的属性的 setter 方法,然后通过getter方法获取变量。
如果我们的变量采用下划线的方式,或者横线的方式配置,还能不能读取到呢?
  依然可以读取到,配置方式比较灵活。
另外@ConfigurationProperties 也可以和 validation 注解一起使用的,能够避免我们在开发环境中产生不必要的错误。加入validation 依赖包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
我们把配置文件里面的变量配置不规:

修改配置,加入validation 注解:

当我们启动程序,会发现直接报错了,无法启动,控制台打印如下信息:
 特别适用,配置十分灵活和安全。
那如果我想要将oauth的信息单独放在其他配置文件里呢,可以配合这个注解一起使用,@PropertySource(value ={""}) 卧槽嘞?这里小编发现了一个坑。

我的配置文件这样写,可以吗?没毛病啊!!!!!!!!!!!!!
  启动直接炸掉,根本在oauth.yml配置文件里面读取不到,我炸了。
 然后一波操作,还能干啥?找度娘吧,哎!
2.5.2. Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The YamlPropertiesFactoryBean loads YAML as Properties and the YamlMapFactoryBean loads YAML as a Map. You can also use the YamlPropertySourceLoader class if you want to load YAML as a Spring PropertySource. Spring Framework提供了两个方便的类,可用于加载YAML文档。 YamlPropertiesFactoryBean将YAML作为属性加载,而YamlMapFactoryBean将YAML作为Map加载。 如果要将YAML加载为Spring PropertySource,也可以使用YamlPropertySourceLoader类。
翻译成人话:Spring Boot对外部化配置提供了强大的支持。 另外,可以使用不同的方式和格式直接读取Spring Boot应用程序中的属性。但是,默认情况下,@PropertySource不会加载YAML文件。
这不废话吗?难道换个后缀名就ok了,换成oauth.properties ?我怀着揣测的心情再尝试了一波,如果再失败,以下文字将不会出现在本文!!!!

 我不服,我不服,有解决方式吗》我有强迫症,就想用yml,我爱得深沉啊!!!
 你管我,就不服,操作一波。自定义PropertySourceFactory,从Spring 4.3开始,@PropertySource带有factory属性。 可以利用它来提供PropertySourceFactory的自定义实现,该实现将处理YAML文件处理。
实现思路:
定义一个YamlPropertySourceFactory,实现PropertySourceFactory,重写createPropertySource方法。
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
Properties properties = factory.getObject();
assert properties != null;
return new PropertiesPropertySource(Objects.requireNonNull(resource.getResource().getFilename()), properties);
}
}
将自定义生成的Properties对象传入PropertiesPropertySource中产出一个新的PropertySource对象,结束!!!

再次启动测试:

总结
Spring Boot的注解绑定类型安全的 Java Bean 是非常强大的,在开发中经常会用到,选择一种适合项目的方式,注解编程,无比强大,赞啊!!!!!!!!!!!!!!!!
|