Spring Boot 多环境配置: No active profile set, falling back to 1 default profile: 'default'
Spring Boot 多环境配置:No active profile set 问题解决
在 Spring Boot 项目中,使用 profiles 可以方便地管理不同环境的配置。本文将详细讲解如何解决 No active profile set, falling back to 1 default profile: 'default' 错误,并介绍多环境配置的最佳实践。
问题描述
在打包 Spring Boot 项目时,即使将 application-prod.properties 文件包含在 target 目录下,仍然出现 No active profile set, falling back to 1 default profile: 'default' 错误信息。
原因分析
出现此错误的主要原因是,在打包过程中没有明确指定要激活的 profile。Spring Boot 默认会使用 default 配置文件,如果未设置 profile,就会使用该默认配置文件。
解决方法
-
在
pom.xml文件中配置profilexml <profiles> <!-- 开发环境 --> <profile> <id>dev</id> <properties> <profiles.active>dev</profiles.active> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <!-- 生产环境 --> <profile> <id>prod</id> <properties> <profiles.active>prod</profiles.active> </properties> </profile> </profiles>在上述配置中,
dev配置文件被设置为默认激活的配置文件,prod配置文件需要通过命令行参数指定激活。 -
使用
-D参数指定激活的profile在打包时,使用
-Dspring.profiles.active=prod参数来激活prod环境的配置文件。例如:bash mvn clean package -Dspring.profiles.active=prod
其他配置
-
在
build标签中配置资源文件路径xml <resources> <resource> <directory>src/main/resources/${profiles.active}</directory> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources>该配置将根据激活的
profile自动选择不同的资源文件。 -
使用
spring-boot-maven-plugin打包xml <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin>该插件可以方便地将项目打包成可执行的 Jar 包或 War 包。
总结
在使用 Spring Boot 多环境配置时,需要在打包时明确指定激活的 profile,并根据 profile 配置不同的资源文件。通过以上步骤,可以轻松解决 No active profile set 错误,并实现灵活的多环境配置。
原文地址: https://www.cveoy.top/t/topic/lPVo 著作权归作者所有。请勿转载和采集!