指定Dev Profile启动Spring时仍加载Prod配置的问题
问题现象
使用命令 ./mvnw -Pdev spring-boot:run 以Dev Profile启动Spring应用时,应用意外加载了Prod环境的配置,尝试连接不存在的mysql主机,抛出连接错误,不符合Dev环境仅加载对应配置的预期。
相关配置
application.yaml 配置
spring: application: name: test profiles: active: '@profileActive@' server: port: 8081 #dev config --- spring: config: active: on-profile: dev jpa: hibernate: ddl-auto: update show-sql: true datasource: url: jdbc:mysql://localhost:3306/db username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver #prod config --- spring: config: active: on-profile: prod jpa: hibernate: ddl-auto: update show-sql: true datasource: url: jdbc:mysql://mysql:3306/db username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
pom.xml 相关配置
<resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <includes> <include>**/*.yaml</include> </includes> </resource> </resources> </build> <profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <build.profile.id>dev</build.profile.id> <profileActivate>dev</profileActivate> </properties> </profile> <profile> <id>prod</id> <activation> <activeByDefault>false</activeByDefault> </activation> <properties> <build.profile.id>prod</build.profile.id> <profileActivate>prod</profileActivate> </properties> </profile> </profiles>
问题原因
你误用了spring.config.active.on-profile配置项,这个参数的作用是激活额外的配置文件,而非限定当前配置片段仅在对应Profile下生效。正确的Profile片段标识应该是spring.profiles,当前写法导致Prod的配置片段没有被正确限定,Spring会默认加载该片段,最终覆盖或合并了Dev的数据源配置。
解决方案
修改application.yaml中的Profile标识,将spring.config.active.on-profile替换为spring.profiles,确保每个配置片段仅在对应Profile激活时加载:
spring: application: name: test profiles: active: '@profileActive@' server: port: 8081 #dev config --- spring: profiles: dev jpa: hibernate: ddl-auto: update show-sql: true datasource: url: jdbc:mysql://localhost:3306/db username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver #prod config --- spring: profiles: prod jpa: hibernate: ddl-auto: update show-sql: true datasource: url: jdbc:mysql://mysql:3306/db username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
修改后重新执行./mvnw -Pdev spring-boot:run,应用只会加载Dev对应的配置片段,连接localhost上的MySQL,不会再加载Prod配置。
内容的提问来源于stack exchange,提问作者SlimenTN
相关产品推荐
相关产品推荐

