SpringBoot 之 Profile
一个应用为了在不同的环境下工作,常常会有不同的配置,代码逻辑处理。Spring Boot 对此提供了简便的支持。
关键词:
@Profile
、spring.profiles.active
区分环境的配置
properties 配置
假设,一个应用的工作环境有:dev、test、prod
那么,我们可以添加 4 个配置文件:
applcation.properties
- 公共配置application-dev.properties
- 开发环境配置application-test.properties
- 测试环境配置application-prod.properties
- 生产环境配置
在 applcation.properties
文件中可以通过以下配置来激活 profile:
1 | spring.profiles.active = test |
yml 配置
与 properties 文件类似,我们也可以添加 4 个配置文件:
applcation.yml
- 公共配置application-dev.yml
- 开发环境配置application-test.yml
- 测试环境配置application-prod.yml
- 生产环境配置
在 applcation.yml
文件中可以通过以下配置来激活 profile:
1 | spring: |
此外,yml 文件也可以在一个文件中完成所有 profile 的配置:
1 | # 激活 prod |
注意:不同 profile 之间通过 ---
分割
区分环境的代码
使用 @Profile
注解可以指定类或方法在特定的 Profile 环境生效。
修饰类
1 |
|
修饰注解
1 |
|
修饰方法
1 |
|
激活 profile
插件激活 profile
1 | spring-boot:run -Drun.profiles=prod |
main 方法激活 profile
1 | --spring.profiles.active=prod |
jar 激活 profile
1 | java -jar -Dspring.profiles.active=prod *.jar |
在 Java 代码中激活 profile
直接指定环境变量来激活 profile:
1 | System.setProperty("spring.profiles.active", "test"); |
在 Spring 容器中激活 profile:
1 | AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); |
示例源码
示例源码:spring-boot-profile
参考资料
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 coder-xuyong!
评论