gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:59:48 25 4
gpt4 key购买 nike

我需要在项目位置之外访问 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com