I want to read values via the Spring @Value(...)
annotation programmatically. Call the Spring code programmatically behind the @Value(...)
annotation.
All the examples I have found on this topic explain how to add a new *.properties
file to the Spring context. But in my case, I use an external key/value store, the Hashicorp consul
and I want to read values from this external KV store. The Spring annotation works fine. It reads the values from the consul
properly.
My code must be transparent from the application point of view. I do not want to see any consul
related code in my project like this:
ConsulClient consulClient = null;
consulClient.getKVValue("key").toString();
If I change the KV store behind the application, I do not want to modify the Java code.
If possible, I would like to invoke programmatically the Spring code behind the @Value(...)
annotation and get the value for a key on a standard Spring way.
In order to programatically load values from property files in Spring you can use the Environment
bean (see javadoc)
For that simply autowire the bean, and use the getProperty()
method:
@Component
public class Foo {
@Autowired
private Environment environment;
public void yourMethod() {
String value = this.environment.getProperty("key");
// do whatever
}
}