【问题标题】:How to add properties to a spring boot application context on run time如何在运行时将属性添加到 Spring Boot 应用程序上下文
【发布时间】:2020-12-03 13:30:20
【问题描述】:

我有一个 Spring Boot 应用程序和一个属性文件 config.properties,其中的值是加密的(请参见下面的示例)

config.properties

myapp.property1={5AES123}SafeR70/wqqwwqwqwqwqsdaWQmNs+O2afeIU/1MHoCWvTgxUYA30C/rrei4\=
myapp.property2={5AES342}MareV70/PLNqsasasaa*ksueoHH+O2afeIU/1MHoCWvTgxUYJQ30C/7rei4\=
myapp.property3={5AES111}TutoV10/xdtghshI5CVULQ7uevr+O2afeIU/1MHoCWvTgxUYJQ30C/1rei4\=

我正在使用特殊的 API(作为 POM 依赖项添加到我的应用中)来解密这些值。

请在下面找到伪代码,以更好地解释我的意图以及我希望在一天结束时拥有的东西。

public static void main(String[] args) {

  // 1. decrypt the properties values of the config.properties using my special API package.
  List<MyPropDecrypted> myPropDecryptedLst = mySpecialAPIPack.decrpyt("config.properties");

  // 2. get the spring context
  myAppSpringContext = getSpringContext();

  //3. add the decrypted properties to the spring context from step 2.
  int idx = 0;
  for (MyPropDecrypted myPropDecrypted : myPropDecryptedLst){
     idx++;
     myAppSpringContext.setProperty("myapp.property"+idx, myPropDecrypted.getDecrypteValue();
  }

  SpringApplication.run(Application.class, args);
}

我的问题是如何以编程方式将那些解密的(使用我的特殊 API)属性添加/注入到 spring 上下文中,以便我可以像从属性文件加载的属性一样使用它(@Value("${myapp.property1 }"))?

【问题讨论】:

    标签: java spring spring-boot properties


    【解决方案1】:

    我建议你创建一个这样的配置类:

     @ConfigurationProperties
        @Configuration
        class MyConfig{
        
       public Map<String,String > myapp;
        
         public String getproperty1() {
          return myapp.get("property1");
        }
        
          public String getProperty2() {
        //
        }
        
        //getters and setter for all the three properties
        
        }
    

    现在更新您的 PSEUDO 代码以使用 setter 方法设置解密的值。然后,您可以在任何其他类中注入 MyConfig 类并获取值。

    【讨论】:

    • 这是一个非常好的主意,我想我会在一天结束时使用。它本来是理想的,而不是两者(两者之间的组合, Configuration 和 Value )。假设在运行时 spring 能够通过 Configuration 设置这些值并使这些属性可用于 Value(${myprop1})。
    • 我的意图是找到一种方法来获取这些值在每个类中自动装配 MyConfig 我需要这些值但让 Value(${...}) 完成这项工作自动地。那是因为我尽量避免更改现有类,这些类通过 Value(${...}) 获取属性值
    【解决方案2】:

    您可以使用 Spring Cloud Config 并按照此处的说明实现自定义 EnvironmentRepository bean:

    自定义复合环境存储库 除了使用 Spring Cloud 中的环境存储库之一,您还可以提供自己的 EnvironmentRepository bean,作为复合环境的一部分。为此,您的 bean 必须实现 EnvironmentRepository 接口。如果您想在复合环境中控制自定义 EnvironmentRepository 的优先级,您还应该实现 Ordered 接口并覆盖 getOrdered 方法。如果您不实现 Ordered 接口,则您的 EnvironmentRepository 的优先级最低。

    Docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-22
      • 2017-10-11
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      相关资源
      最近更新 更多