Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value in .properties file directly from Spring context

Tags:

spring

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

like image 747
user1052610 Avatar asked Oct 26 '25 11:10

user1052610


2 Answers

You need to get access to the BeanFactory:

ctx.getBeanFactory().resolveEmbeddedValue("${key-name}");
like image 87
Andrei Stefan Avatar answered Oct 29 '25 01:10

Andrei Stefan


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

like image 24
Alex Avatar answered Oct 29 '25 01:10

Alex