繁体   English   中英

如何在运行时向 spring 启动应用程序上下文添加属性

[英]How to add properties to a spring boot application context on run time

我有一个 Spring 启动应用程序和一个属性文件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}") )?

您可以使用 Spring Cloud Config 并实现自定义 EnvironmentRepository bean,如下所述:

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

文档

我建议您像这样创建配置 class :

 @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 方法设置解密的值。 然后,您可以在任何其他 class 中注入 MyConfig class 并获取值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM