1

I am trying to read secrets on application startup and make it available for

  1. Other classes to access
  2. And to access the value from other yaml files (for integration with other tools Eg.api keys).

The springboot application uses EnvironmentPostProcessorImpl class that reads the secrets to a Map<String,String> on startup.

I would like to understand what would be a correct way to make the Map<String,String> in EnvironmentPostProcessorImpl class available to other Java classes to access and in yaml files using placesholders Eg. url: "${URL}", if that's possible? Any reference would be helpful.

  • Does this answer your question? [How to pass a Map with application.properties](https://stackoverflow.com/questions/26275736/how-to-pass-a-mapstring-string-with-application-properties) – Pirate Jun 20 '21 at 09:33
  • @Pirate The examples show how to bind values from the .properties and access in the Java code, right. I am looking for the other way around. To add, When spring calls EnvironmentPostProcessorImpl class, the container won't be initialized and no Beans would be available. Something I know is to put the map to Env object to access form code. But I'd like to know how to get the values in yaml. Looking for possible ways to achieve this. – continuousLearner Jun 20 '21 at 09:44

2 Answers2

1

In your EnvironmentPostProcessor implementation, you should create a MapPropertySource from your Map<String, String> and add it to the ConfigurableEnvrionment that is being post-processed. This will allow components in your application to access those properties using @ConfigurationProperties, @Value, via property placeholders , etc.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Thanks @Andy. Here is how I use it now - `configurableEnvrionment.getPropertySources().addLast(new MapPropertySource("dataConfig", dataConfig));`. Calling getPropertySources on ConfigurableEnvironment will get me the value from the class. Would be helpful if you could share how I can refer this data in the yaml? – continuousLearner Jun 20 '21 at 12:48
  • 1
    You can use placeholders in the value of a property in yaml and properties files. The placeholders are then resolved when the property is retrieved from the environment. – Andy Wilkinson Jun 20 '21 at 13:09
0

Spring Boot has a lot of ways to configure its Environment. Here is documentation reference for configuration and Spring Boot blog with configuration tips.

If you need to inject some Spring variable via OS environment variables, you need to replace all . to _ and remove all - symbols. For example, if you need to inject property my-prefix.api.url, you need to declare environment variable MYPREFIX_API_URL and then you can access your variable just as regular Spring variable.

@Value("${my-prefix.api.url}")
String url;
geobreze
  • 2,274
  • 1
  • 10
  • 15