4

In a standard Spring application, a PropertyPlaceholderConfigurer may be defined, which will load one or more property files. The values defined in the files will then be visible to the rest of the application, both in XML ("${}") and Java (@Value).

Is there a way, once a context has been loaded, to get such a property value from the context itsef, in the similar way that a bean can be retrieved (ctx.getBean("bean-name")) ?

I tried the following, but it does not work:

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:META-INF/spring/spring-context.xml");
ctx.refresh();
ctx.start();
ctx.getEnvironment().getProperty("key-name")); // RETURNS NULL

Thanks

user1052610
  • 4,440
  • 13
  • 50
  • 101

3 Answers3

5

You need to get access to the BeanFactory:

ctx.getBeanFactory().resolveEmbeddedValue("${key-name}");
Andrei Stefan
  • 51,654
  • 6
  • 98
  • 89
  • 1
    does not work with Spring 5 anymore, sadly, methods are not available and I did not find a replacement. – Gregor Aug 20 '18 at 17:16
  • 2
    You can use Environment: `env.resolvePlaceholders("${key-name:default-value}")` To inject Environment your class can implement `EnvironmentAware` or you can Environment from from `ApplicationContext`, as it's extending `EnvironmentCapable` class. – Augustin Ghauratto Dec 31 '18 at 13:22
2

See this answer for a simple approach that could work by adding an interface called EmbeddedValueResolverAware to the class in which you want to resolve the property values.

https://stackoverflow.com/a/16106729/1325237

Community
  • 1
  • 1
Alex
  • 855
  • 7
  • 21
  • this is the only way that worked for me in a simple way with Spring 5, without having to wrap any Spring classes. – Gregor Aug 20 '18 at 17:26
0

The embedded variable can be retrieved from the Environment by using the resolvePlaceholders method. Note that you need to wrap it in ${}:

ctx.getEnvironment().resolvePlaceholders("${key-name}")
M. Justin
  • 14,487
  • 7
  • 91
  • 130