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

Avi*_*pta 3 java spring-profiles spring-boot spring-properties

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

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

Run Code Online (Sandbox Code Playgroud)

现在,我想使用主动配置文件实现相同的目的。如果开发人员配置文件处于活动状态,则需要获取application-dev.properties,如果阶段配置文件处于活动状态,则需要获取application-stage.properties,依此类推。

我正在将Windows平台和JAVA 8与Spring Boot 1.5.x一起使用

我尝试在application.properties文件中设置活动配置文件。但这不起作用

spring.profiles.active=dev
Run Code Online (Sandbox Code Playgroud)

Mar*_*sic 5

Spring Boot 1.5.X的解决方案

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

-Dspring.config.location=file:${user.home}/file/path/
Run Code Online (Sandbox Code Playgroud)

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

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

现在,如果您application-dev.properties的自定义配置文件夹中有一个文件,则只需application.properties添加以下内容即可激活默认文件中的配置文件:

spring.profiles.active=dev
Run Code Online (Sandbox Code Playgroud)

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

@Component
public class PropConfig implements InitializingBean {
Run Code Online (Sandbox Code Playgroud)

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


Spring Boot 2.X的解决方案

该方法主要与Spring Boot 1.5.X相同,但有一点区别。

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

使用spring.config.location配置自定义配置位置后,它们将替换默认位置。(来源:Spring Boot文档

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

-Dspring.config.additional-location=file:${user.home}/file/path/
Run Code Online (Sandbox Code Playgroud)

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

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

  • 在这种情况下,我更喜欢另一种方式 - 使用 JVM 参数而不是环境变量。如果您只能使用环境变量,我认为为每个项目提供单独值的唯一方法是使用不同的用户运行每个应用程序,然后为每个用户设置不同的环境变量值(您可以在此处找到操作方法:https://serverfault.com/questions/583185/creating-an-environment-variable-for-a-specific-user)。但我不知道您的应用程序是否可以有多个用户。你能尝试一下 JVM arg 方法吗? (2认同)