Doches
Doches

Reputation: 3468

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

Upvotes: 19

Views: 25771

Answers (3)

jediz
jediz

Reputation: 4717

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

Upvotes: 0

Wilson Campusano
Wilson Campusano

Reputation: 616

inject BeanFactory into your bean.

 @Autowired
 BeanFactory factory;

then cast and get the property from the bean

((ConfigurableBeanFactory) factory).resolveEmbeddedValue("${propertie}")

Upvotes: 4

Sangam Belose
Sangam Belose

Reputation: 4506

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

Upvotes: 20

Related Questions