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);
}
To dynamically fetch any value enclose the property with @ both at the beginning and the end. In the above example the value for project.name is populated dynamically.
Spring Boot - Using ${} placeholders in Property Files Spring also provides it's own variable substitution in property files. We just need to use ${someProp} in property file and start the application having 'someProp' in system properties or as main class (or jar) argument '--someProp=theValue'.
@DynamicPropertySource instead is used to: make it easier to set configuration properties from something else that's bootstrapped as part of running an integration test. This helps also setting up integration tests with Test Containers, getting rid of a lot of boilerplate code.
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
inject BeanFactory into your bean.
@Autowired
BeanFactory factory;
then cast and get the property from the bean
((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With