本篇记录一下 springboot 中 profile 相关配置和使用技巧
在开发过程中 常常会有很多环境 比如 dev prod qa 等等 每个环境的配置是不同的, 那么在springboot 中可以利用 profile 很轻松的将各个环境 隔离分开 ,并且很容易维护
1. 单文件 多环境
在单个的 application.yaml 中 可以通过 — 来将环境分割开 ,最上面的是 各个环境的通用部分
, 每个环境用 spring.profiles: 指定环境名称
management:
endpoints:
web:
exposure:
include: env,conditions
endpoint:
health:
show-details: always
--- # 分隔符最上面 属于通用部分 每个下面的环境 都公用
spring:
profiles: dev #表明这一块是 dev 环境
server:
port: 8081
---
spring:
profiles: prod #表明这一块是 prod 环境
server:
port: 8082
2.多文件 多环境
可以把不通的环境 分为不通的文件 通过 application-{环境名称}.yaml 的方式 区分不同的 环境.只需要给定激活的参数接口
2.1 application.yaml
在主文件中 放置 通用的配置
management:
endpoints:
web:
exposure:
include: env,conditions
endpoint:
health:
show-details: always
spring:
profiles:
active: prod # 表明激活哪个profile
2.2 application-dev.yaml
server:
port: 8081
2.3 applicaiton-prod.yaml
server:
port: 8082
3.激活 profile 方式和顺序
上面是关于如何把不同环境的配置分开, 可以在单个文件中分开, 也可以通过不通文件分开, 下面来看看 如何去激活某个环境
3.1 通过 通用配置部分激活
在单文件中 在通用部分添加 如下配置 即可激活某个环境profile
spring: profiles: active: prod #表明 激活哪个profile
management:
endpoints:
web:
exposure:
include: env,conditions
endpoint:
health:
show-details: always
spring:
profiles:
active: prod #表明 激活哪个profile
--- # 分隔符最上面 属于通用部分 每个下面的环境 都公用
spring:
profiles: dev #表明这一块是 dev 环境
server:
port: 8081
---
spring:
profiles: prod #表明这一块是 prod 环境
server:
port: 8082
3.2 通过 idea 启动配置环境
在idea的启动配置上 可以指定 Active profiles:
此配置优先级要高于 上面配置文件中指定的 配置
3.3 同jar 目录下的application.yaml 配置
如果打成jar 后 上面idea 的配置就无用了, 那么也可以通过在jar 同级目录下存放一个 配置文件,在这个配置文件里面进行指定 环境 优先读取这个
3.4 java -jar 指定
优先级高于 上面的
java -jar springboot-demo-01-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
总结
本篇主要介绍了 springboot 中 profile 的配置方式和技巧, profile 可以在单文件中区分环境 也可以在不同文件 通过application-{环境名称}.yaml 区分
激活profie 的优先级 java -jar > jar 同级目录配置 > jar中配置的环境
原文始发于微信公众号(Johnny屋):SpringBoot Profile 相关配置和使用
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/89865.html