目录:
- properties文件
- yaml文件
- 两种配置方式的比较
一. properties文件
1. 说明
不同环境的配置设置一个配置文件,例如:
- dev环境下的配置配置在application-dev.properties中;
- test环境下的配置配置在application-test.properties中;
- prod环境下的配置配置在application-prod.properties中。
但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件;
我们需要通过一个配置来选择需要激活的环境:
spring.profiles.active=dev
spring.profiles.active可以指定配置环境,如指定为dev就会选择 application-dev.properties 文件作为配置环境,同理,要指定不同的环境配置,只需指定application-xxx.properties的xxx即可。
2. 示例:
如此时创建不同的配置文件:
在主配置文件application.properties 中加入:
spring.profiles.active=dev
在 application-dev.properties 中加入:
server.port=8081
在 application-test.properties 中加入
server.port=8082
启动项目,可以看到端口设置为了8081
springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件:
- 优先级1:项目路径下的config文件夹配置文件 file: ./config/
- 优先级2:项目路径下配置文件:file: ./
- 优先级3:资源路径下的config文件夹配置文件 classpath: ./config/
- 优先级4:资源路径下配置文件: classpath: ./ ----------默认创建application.properties的地方
Controller
@Autowired
private Environment env;
@RequestMapping("/testProfile")
public String testProfile(){
return env.getProperty("profile"); // test
}
3. 结论:
- 各个环境公共的配置写在application.properties中
- 各个模块独有的配置配置在自己的application-{xxx}.properties文件中
- 程序读取的时候优先读取application.properties中选中的profile的配置,若读不到才会从application-{xxx}.properties去读
二. yaml文件
yaml文件切换配置环境与properties文件有所不同,它可以在同一个文件中配置多套环境,只要给每套环境设置名称,在主配置环境中指定即可:
server:
port: 8081
#选择要激活那个环境
spring:
profiles:
active: test
---
server:
port: 8083
spring:
profiles: dev #配置环境的名称
---
server:
port: 8084
spring:
profiles: test #配置环境的名称
测试就发现启动端口是8084,切换环境成功
三. 两种配置方式的比较
- Properties配置多环境,需要添加多个配置文件,YAML只需要一个配件文件,yml文件本身具有区分不同环境的能力
- 书写格式的差异,yaml相对比较简洁,优雅
- YAML的缺点:不能通过@PropertySource注解加载。如果需要使用@PropertySource注解的方式加载值,那就要使用properties文件。