Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 392
Doches Avatar asked Jan 22 '14 07:01

Doches


People also ask

How do you pass dynamic value to application properties in spring boot?

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.

What is ${} in spring?

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'.

What is @DynamicPropertySource?

@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.


2 Answers

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
like image 101
Sangam Belose Avatar answered Sep 23 '22 22:09

Sangam Belose


inject BeanFactory into your bean.

 @Autowired
 BeanFactory factory;

then cast and get the property from the bean

((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")
like image 42
Wilson Campusano Avatar answered Sep 22 '22 22:09

Wilson Campusano