Dynamic @ Value equivalent in Spring?

I have a Spring-installed bean that loads properties using property-placeholder in the associated context.xml :

 <context:property-placeholder location="file:config/example.prefs" /> 

I can access properties using Spring @Value annotations on initialization, for example:

 @Value("${some.prefs.key}") String someProperty; 

... but I need to expose these properties to other (not related to w762>) objects in a common way. Ideally, I could expose them using a method, for example:

 public String getPropertyValue(String key) { @Value("${" + key + "}") String value; return value; } 

... but obviously I cannot use the @Value annotation in this context. Is there a way to access properties loaded using Spring from example.prefs at runtime using keys, for example:

 public String getPropertyValue(String key) { return SomeSpringContextOrEnvironmentObject.getValue(key); } 
+8
java spring properties-file
source share
2 answers

Autowire Environment object in your class. Then you can access the properties using environment.getProperty (propertyName);

 @Autowired private Environment environment; // access it as below wherever required. environment.getProperty(propertyName); 

Also add @PropertySource to the Config class.

 @Configuration @PropertySource("classpath:some.properties") public class ApplicationConfiguration 
+5
source share

enter the BeanFactory into the bean.

  @Autowired BeanFactory factory; 

then open and get the property from bean

 ((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}") 
0
source share

All Articles