ittradco
ittradco

Reputation: 193

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

I have a Spring boot Application and a properties file config.properties where the values are encrypted (please see an example below)

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\=

I'm using a special API (added as POM dependency on my app) to decrypt those values.

Please find below a PSEUDOCODE to explain better my intentions and what I wish I have at the end of the day.

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);
}

My question is how can I programmatically add/inject those decrypted (with my special API) properties to the spring context, so that I can use it like properties loaded from a property file (@Value("${myapp.property1}"))?

Upvotes: 0

Views: 2568

Answers (2)

Umesh Sanwal
Umesh Sanwal

Reputation: 777

I would suggest you to create a configuration class like this :

 @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
    
    }

Now update your PSEUDO code to set the decrypted values using the setter methods. You can then inject MyConfig class in any other class and get the values.

Upvotes: 1

Charles B
Charles B

Reputation: 97

You could use Spring Cloud Config and implement a custom EnvironmentRepository bean as explained here:

Custom Composite Environment Repositories In addition to using one of the environment repositories from Spring Cloud, you can also provide your own EnvironmentRepository bean to be included as part of a composite environment. To do so, your bean must implement the EnvironmentRepository interface. If you want to control the priority of your custom EnvironmentRepository within the composite environment, you should also implement the Ordered interface and override the getOrdered method. If you do not implement the Ordered interface, your EnvironmentRepository is given the lowest priority.

Docs

Upvotes: 1

Related Questions