Solorad
Solorad

Reputation: 914

Get Map of properties from spring-boot Environment

I have such a problem: mine application works with set of other applications. Each of them has some unique property - templateProject-id. So, application.properties looks like

mine.application.basic-project-id.application_1=10200
mine.application.basic-project-id.application_2=10202
mine.application.basic-project-id.application_3=10001

I don't want to store Environment object in my service class. Only Map<String, Long> for pairs (application_name, project_id) So, from that example should contain pairs ("application_1", 10200L), ("application_2",10202L), ("application_3",10001").

Right now I store Environment and with application name I build property name each time and retrieve value.

String projectIdPropertyName = String.format("mine.application.basic-project-id.%s", applicationDescriptor.getName());
String softwareBasicProjectId = Long.valueOf(environment.getProperty(projectIdPropertyName));

Upvotes: 2

Views: 2258

Answers (1)

Stephane Nicoll
Stephane Nicoll

Reputation: 33151

This should work

@ConfigurationProperties("mine.application")
public class ApplicationProperties {

   private Map<String,Long> basicProjectId = new HashMap<>();

   public Map<String,Long> getBasicProjectId() { 
     return basicProjectId;
   }
}


@SpringBootApplication
@EnableConfigurationProperties(ApplicationProperties.class)
public class YourApp { .... }

Then anywhere you need that stuff, just inject ApplicationProperties. If you enable the Spring Boot configuration meta-data annotation processor to your build you'll also get content assistance for that key (and any other key you'd add in that class).

Upvotes: 4

Related Questions