How to programmatically resolve property placeholder in Spring

Since version 3.0, Spring keeps a list of String resolver in the beanFactory. You can use it like this:

String value = appContext.getBeanFactory().resolveEmbeddedValue("${prop}");

The javadoc states this method as for resolving embedded values such as annotation attributes so maybe we are circumventing its usage, but it works.


Since Spring 3.0.3 there is EmbeddedValueResolverAware which will work same way as mentioned by another post which uses appContext.getBeanFactory().resolveEmbeddedValue("${prop}") call.

To solve the problem:

  1. Make your class to implement EmbeddedValueResolverAware interface and you will get resolver injected for you

  2. Then where you will be able to retrieve properties as demonstrated in a code snippet:

    String propertyValue = resolver.resolveStringValue("${your.property.name}");
    

Then your bean does not need to depend on ApplicationContext to retrieve properties you need.