如何根据活动配置文件访问 application-{profile}.properties 文件

How to access application-{profile}.properties file based on active profile

我需要在项目位置之外访问 application.properties 文件。我可以使用以下方法实现相同的目的:

@Component
@PropertySources({
        @PropertySource(value = "file:${user.home}/file/path/application.properties", ignoreResourceNotFound = false) })
public class PropConfig implements InitializingBean {

现在,我想使用活动配置文件实现相同的目的。如果开发配置文件处于活动状态,我需要获取应用程序-dev.properties,如果阶段配置文件处于活动状态,我需要获取应用程序-stage.properties 等等。

I am using Windows platform and JAVA 8 with Spring Boot 1.5.x

我尝试在 application.properties 文件中设置活动配置文件。但是不行

spring.profiles.active=dev

您能否尝试使用 JVM 参数设置活动配置文件,如下所示 - -Dspring.profiles.active=dev

如果您的要求是限制在环境中使用的特定 bean,则可以使用 @Profile("dev") 注释。

此参考可能对您有所帮助 -> https://www.baeldung.com/spring-profiles

Spring 引导 1 的解决方案。5.X

您可以使用以下 JVM 参数通过 运行 您的应用将文件夹添加为自定义配置位置:

-Dspring.config.location=file:${user.home}/file/path/

配置此 JVM 参数后,将自动解析此文件夹中的所有 application-{profile}.properties 个文件。

( 或者,如果你更喜欢使用环境变量而不是 JVM 参数,你可以通过设置 SPRING_CONFIG_LOCATION 环境变量来做同样的事情,例如在 linux终端机:export SPRING_CONFIG_LOCATION=file:${user.home}/file/path/ )

现在,如果您的自定义配置文件夹中有文件 application-dev.properties,通过添加以下内容就足以激活默认 application.properties 文件中的配置文件:

spring.profiles.active=dev

最后,@PropertySources 注释是多余的,您可以将其删除:

@Component
public class PropConfig implements InitializingBean {

参考:https://docs.spring.io/spring-boot/docs/1.5.0.RELEASE/reference/html/boot-features-external-config.html


Spring 启动解决方案2.X

方法与 Spring Boot 1 基本相同。5.X 但略有不同。

在 Spring Boot 2.X 中,spring.config.location 参数的行为与早期版本略有不同。区别在于 Spring Boot 2.X spring.config.location 参数覆盖默认配置位置:

When custom config locations are configured by using spring.config.location, they replace the default locations. (Source: Spring Boot Documentation)

由于将此参数设置为您的自定义配置文件夹会覆盖默认位置(我想丢失默认配置位置上的配置文件不是所需的行为),最好使用新的 spring.config.additional-location 不覆盖但仅扩展默认位置的参数:

-Dspring.config.additional-location=file:${user.home}/file/path/

(或者,如果您更喜欢使用环境变量而不是 JVM 参数,则可以使用 SPRING_CONFIG_ADDITIONAL-LOCATION 环境变量)

参考:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html