Dynamic @Value-equivalent in Spring?

Doches picture Doches · Jan 22, 2014 · Viewed 15.3k times · Source

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);
}

Answer

Sangam Belose picture Sangam Belose · Jun 12, 2017

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