Dynamic property access using Spring 3.1 property abstraction

I am trying to dynamically access properties from Spring's Abstraction of Environment Properties .

I declare my property files as follows:

<context:property-placeholder location="classpath:server.common.properties, classpath:server.${my-environment}.properties" /> 

In the server.test.properties properties server.test.properties I define the following:

 myKey=foo 

Then, given the following code:

 @Component public class PropertyTest { @Value("${myKey}") private String propertyValue; @Autowired private PropertyResolver propertyResolver; public function test() { String fromResolver = propertyResolver.getProperty("myKey"); } } 

When I run this code, I end with propertyValue='foo' , but fromResolver=null ;

Getting propertyValue means that properties are being read (and I know this from other parts of my code). However, trying to find them dynamically does not work.

Why? How can I dynamically search for property values ​​without using @Value ?

+4
source share
2 answers

Just adding <context:property-placeholder/> does not add the new Property property to the environment. If you read an article that you have fully linked, you will see that it offers to register ApplicationContextInitializer to add new PropertySources so that they are accessible the way you try to use them.

+2
source

For this to work, I had to split the property readings into an @Configuration bean as shown.

Here is a complete example:

 @Configuration @PropertySource("classpath:/server.${env}.properties") public class AngularEnvironmentModuleConfiguration { private static final String PROPERTY_LIST_NAME = "angular.environment.properties"; @Autowired private Environment environment; @Bean(name="angularEnvironmentProperties") public Map<String,String> getAngularEnvironmentProperties() { String propertiesToInclude = environment.getProperty(PROPERTY_LIST_NAME, ""); String[] propertyNames = StringUtils.split(propertiesToInclude, ","); Map<String,String> properties = Maps.newHashMap(); for (String propertyName : propertyNames) { String propertyValue = environment.getProperty(propertyName); properties.put(propertyName, propertyValue); } return properties; } } 

Then, the property set is entered in another place that you want to use.

+1
source

Source: https://habr.com/ru/post/1482299/


All Articles