【问题标题】:In a SpringBoot application, how to set @ConfigurationProperties(prefix = ...) dynamically?在 SpringBoot 应用程序中,如何动态设置 @ConfigurationProperties(prefix = ...)?
【发布时间】:2018-11-08 05:47:12
【问题描述】:

我编写了一个小应用程序,其中包含一个 @ConfigurationProperties(prefix = ...) 注释来为其中一个 bean 加载正确的配置。这一直运行良好,并且在针对不同环境进行测试时,我一直在手动更改我的 IDE 中的 prefix 值。

现在我需要清理它并确保应用程序可以在不同的环境中运行而无需重新编译。该值需要参数化。如何在运行时动态设置前缀?

相关问题

另一个问题引用了一个不起作用的特定方法,使用 spEL:

Property in @ConfigurationProperties prefix

这个说你不能用YAML(我不在乎)

How to implement dynamic @ConfigurationProperties Prefix

我正在寻找更普遍的解决方案。

【问题讨论】:

    标签: spring-boot


    【解决方案1】:

    我认为您所要求的内容与弹簧/弹簧靴实践相矛盾。

    配置属性键在 spring 中必须是静态的。

    这意味着,在所有环境中,必须存在相同的配置属性键。

    属性的值会因环境而变化

    对于本地开发,您可能需要解决:

    例子:

    my.db.host = localhost
    

    但是,对于生产,您需要以下内容:

    my.db.host = myproduction.db.host.real.address.goes.here
    

    从 Spring 的角度来看,您有:

    @ConfigurationProperties(prefix="my.db") 
    class MyDbProperties {
       String host;
       ...
    }
    

    现在的问题是如何更改 dev/stage/local/production 等的属性值集。

    春天的答案是“profiles”

    在 Spring Boot 中,您可以使用以下方式启动应用程序:

    --spring.profiles.active=dev
    

    在这种情况下,application-dev.properties 将自动加载(当然是 yaml)

    所以你应该为每个环境创建一个文件,并在其中放置特定的值:

    application-local.properties

    my.db.host=localhost
    

    application-prod.properties

    my.db.host=myproduction.db.host.real.address.goes.here
    

    【讨论】:

    • 不是我想听到的,但似乎是正确的答案。我将代码更改为在单独的文件中使用配置文件,而不是前缀。
    猜你喜欢
    • 2018-01-15
    • 2019-07-05
    • 2021-09-05
    • 2016-01-09
    • 2020-02-28
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多