3-5.多环境开发控制
约 426 字大约 1 分钟
2025-06-23
当 Maven 和 Spring Boot 同时配置多环境时,需要理清它们之间的关系,明确谁应该具有主导地位。由于 Maven 负责项目构建和包的生成,而 Spring Boot 的主要目标是简化开发,因此应该以 Maven 的配置为主。
解决方案:以 Maven 为主导,Spring Boot 读取 Maven 配置
1. 在 Maven 中设置具体环境
通过 Maven 的 <profiles>
标签,使用属性方式来区分不同的环境。
<profiles>
<profile>
<id>env_dev</id>
<properties>
<profile.active>dev</profile.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault><!--默认启动环境-->
</activation>
</profile>
<profile>
<id>env_pro</id>
<properties>
<profile.active>pro</profile.active>
</properties>
</profile>
</profiles>
上述代码定义了两个 profile,env_dev
和 env_pro
,分别代表开发环境和生产环境。通过 <properties>
标签设置 profile.active
属性来指定当前激活的环境。<activation>
标签中的 <activeByDefault>true</activeByDefault>
表示默认激活 env_dev
环境。
2. 在 Spring Boot 中读取 Maven 设置的值
在 Spring Boot 的 application.yml
或 application.properties
文件中,使用 @属性名@
的语法来读取 Maven 中配置的属性值。
spring:
profiles:
active: @profile.active@
在上面的 YAML 配置文件中,spring.profiles.active
属性的值被设置为 @profile.active@
,这会指示 Spring Boot 从 Maven 的 profile.active
属性中读取当前激活的 profile。通过这种方式,Spring Boot 能够与 Maven 的环境配置保持同步。
总结
- 当 Maven 和 Spring Boot 同时进行多环境控制时,应以 Maven 为主导。Spring Boot 通过
@... @
占位符读取 Maven 对应的配置属性值。 - 基于 Spring Boot 读取 Maven 配置属性的前提下,如果在 IDEA 下测试工程时 pom.xml 每次更新需要手动 compile 方可生效。