'Dynamic @Value-equivalent in Spring?
I have a Spring-managed bean that loads properties using a property-placeholder in its associated context.xml:
<context:property-placeholder location="file:config/example.prefs" />
I can access properties using Spring's @Value annotations at initialisation, e.g.:
@Value("${some.prefs.key}")
String someProperty;
...but I need to expose those properties to other (non-Spring managed) objects in a generic way. Ideally, I could expose them through a method like:
public String getPropertyValue(String key) {
@Value("${" + key + "}")
String value;
return value;
}
...but obviously I can't use the @Value annotation in that context. Is there some way I can access the properties loaded by Spring from example.prefs at runtime using keys, e.g.:
public String getPropertyValue(String key) {
return SomeSpringContextOrEnvironmentObject.getValue(key);
}
Solution 1:[1]
Autowire the Environment object in your class. Then you will be able to access the properties using environment.getProperty(propertyName);
@Autowired
private Environment environment;
// access it as below wherever required.
environment.getProperty(propertyName);
Also add @PropertySource on Config class.
@Configuration
@PropertySource("classpath:some.properties")
public class ApplicationConfiguration
Solution 2:[2]
inject BeanFactory into your bean.
@Autowired
BeanFactory factory;
then cast and get the property from the bean
((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")
Solution 3:[3]
You can have Spring inject the properties into a map, with a lot of benefits. The keys would be the dynamic part.
https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/reference/html/boot-features-external-config.html#boot-features-external-config-complex-type-merge displays the following example:
@ConfigurationProperties("acme")
public class AcmeProperties {
private final Map<String, MyPojo> map = new HashMap<>();
public Map<String, MyPojo> getMap() {
return this.map;
}
}
Properties
acme:
map:
key1:
name: my name 1
description: my description 1
---
spring:
profiles: dev
acme:
map:
key1:
name: dev name 1
key2:
name: dev name 2
description: dev description 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Wilson Campusano |
| Solution 3 | jediz |
