SpringBoot多环境配置
springboot在创建空项目时,会生成一个application.propertites的配置文件,可以在该文件中配置项目所需要的参数配置。通常的项目都有开发环境、测试环境和生产环境等,一个配置文件可能就要换来换去,springboot专门为适应这种情况做了优化。可以分环境来读取配置文件。
springboot的配置文件常见的有两种格式,一种是application.yml(或application.yaml),另一种是application.propertites。
先以propertites类型配置为例:
#application.properties
server.port=8092
spring.profiles.active=dev
demo="common"
#application-dev.properties
demo="dev"
#application-test.properties
demo="test"
如果application.properties中不配置spring.profiles.active=dev,程序会默认加载application.properties,不会加载dev,如果配置了spring.profiles.active=dev,会加载application.properties,也会加载dev,此时demo的配置会被dev中的demo覆盖。但是application-test.properties始终不会加载,这样就实现了多环境配置。
yml或yaml类型的配置和propertites类型的方法类似:
#application.yml
server:
port: 8092
spring:
profiles:
active: dev
demo: common
#application-dev.yml
demo: "dev"
#application-test.yml
demo: "test"
结论和上面是一样的,要注意的是:和"之间要有个空格。
springboot既然支持这几种类型的配置文件,所以也是支持各种类型混用的,比如:
#application.yml
server:
port: 8092
spring:
profiles:
active: dev
demo: common
#application-dev.properties
demo="dev"
#application-test.properties
demo="test"
把application.properties改为application.yml也是可以使用的。如果两个同时存在哪?也没问题,springboot有默认的加载顺序,即yml->yaml->properties,后读取的会覆盖先读取的,此例子中如果两个都存在,则会以application.properties文件中的demo值为最终值。
附:
简单的一个Controller验证:
@RestController
public class MyController {
@Value("${demo}")
private String demo;
@GetMapping("/demo")
public String getDemo(){
return demo;
}
}