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

标签 java spring-boot spring-profiles spring-properties

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

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

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

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

我尝试在 application.properties 文件中设置 Activity 配置文件。但是没用

spring.profiles.active=dev

最佳答案

Spring Boot 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}/文件/路径/ )

现在,如果您的自定义配置文件夹中有文件 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 Boot 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

关于java - 如何根据 Activity 配置文件访问 application-{profile}.properties 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56888575/

相关文章:

java - 如何在spring boot中注册jpa转换器?

spring - 使用 RestController 接受字符串和 XML 数据

java - 在运行时排除 Spring 配置文件的故障

java - 在 groovy 中创建许多函数会产生多少开销

java - TableViewer 如何使用编辑支持设置单元格的插入符位置并删除 FULL_SELECTION

java - 在像 Stream.reduce() 这样的 API 中选择不变性的充分理由是什么?

java - 连续循环直到满足条件

gradle - 在使用 Gradle、Spring Boot 插件和 Nexus 的安装任务期间找不到工件

spring-boot - Yml 配置文件 "Inheritance"与 Spring Boot

java - JUnit + Spring 配置文件 : could not load JDBC driver class