SpringBoot多环境配置

为了让 SpringBoot 更好的生成配置元数据文件,我们需要添加如下依赖,该依赖只会在编译时调用,所以不用担心会对生产造成影响

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

在真实的应用中,常常会有多个环境(如:开发,测试,生产等),不同的环境数据库连接都不一样,这个时候就需要用到spring.profile.active 的强大功能了,它的格式为 application-{profile}.properties,这里的 application 为前缀不能改,{profile} 是我们自己定义的。

1. 创建 application-dev.properties文件,内容为:

server.servlet.context-path=/dev

2. 创建application-test.properties文件,内容为:

server.servlet.context-path=/test

3. 创建application-prod.properties文件,内容为:

server.servlet.context-path=/prod

4. 在 application.properties 中添加内容:

spring.profiles.active=dev

5. 访问地址 http://localhost:8080/properties/2无效,  正确地址为 http://localhost:8080/dev/properties/2

总结:激活不同的配置读取的属性值是不一样的

原文地址:https://www.cnblogs.com/yangjiming/p/10033319.html