3-1.多环境开发(yaml单一文件版)
约 400 字大约 1 分钟
2025-06-23
多环境开发指的是针对不同的环境(例如开发、测试、生产环境)设置不同的配置属性。这样可以确保应用程序在不同环境中运行时,能够使用正确的配置,而无需修改代码。
1. YAML 中设置多环境
在 YAML 文件中,可以使用三个减号 ---
来分隔不同的环境配置。
例如,以下 YAML 文件定义了两组环境配置:
server:
port: 80
---
server:
port: 81
2. 区分不同环境
为了区分不同的环境,可以为每个环境指定一个名称,即 profile。使用 spring.profiles
属性来定义 profile 名称。
spring:
profiles: pro
server:
port: 80
---
spring:
profiles: dev
server:
port: 81
上述配置定义了两个 profile,分别是 pro
(生产环境) 和 dev
(开发环境)。
3. 激活指定环境
可以使用 spring.profiles.active
属性来指定默认启动哪个环境。
spring:
profiles:
active: pro # 启动 pro 环境
---
spring:
profiles: pro
server:
port: 80
---
spring:
profiles: dev
server:
port: 81
在上面的例子中,spring.profiles.active: pro
表示默认启动 pro
环境。
4. 添加更多环境
可以根据需要添加更多环境配置,例如测试环境。
spring:
profiles:
active: pro # 启动 pro 环境
---
spring:
profiles: pro
server:
port: 80
---
spring:
profiles: dev
server:
port: 81
---
spring:
profiles: test
server:
port: 82
5. 标准格式
需要注意的是,spring.profiles
这种环境名称定义格式已经过时。标准的 YAML 格式如下:
spring:
config:
activate:
on-profile: pro
这种格式使用 spring.config.activate.on-profile
属性来指定 profile 名称。