3
votes

Do you know how to use Spring internal Spel Expression Parser in order to parse a String that contains bean reference of the Spring Application Context ?

I have already seen that SpelExpressionParser could be use with a StandardEvaluationContext that define somes explicit user variables.

I'm looking for a solution to directly use the Spring internal Spel Expression Parser binding to the whole Spring Application Context. The idea is to use a string template with the same capabilities of @Value SPEL annotations.

3

3 Answers

0
votes

I found the solution by using :

private Object resolveExpression(String expression) {
    String placeholdersResolved = applicationContext.getBeanFactory().resolveEmbeddedValue(expression);
    BeanExpressionResolver expressionResolver = applicationContext.getBeanFactory().getBeanExpressionResolver();
    return expressionResolver.evaluate(placeholdersResolved, new BeanExpressionContext(applicationContext.getBeanFactory(), null));
}

resolveEmbeddedValue replace ${} expression with properties place holder.

evaluate resolve #{} expression with Application Context Bean Factory

0
votes

You can use EmbeddedValueResolver to achieve the same capabilities as for @Value annotations:

// can be autowired or fetched from ConfigurableApplicationContext.getBeanFactory()
ConfigurableBeanFactory configurableBeanFactory; 

EmbeddedValueResolver embeddedValueResolver = new EmbeddedValueResolver(configurableBeanFactory);
System.out.println(embeddedValueResolver.resolveStringValue("${someProperty}");
System.out.println(embeddedValueResolver.resolveStringValue("#{@foo.calcValue(123)}");
0
votes
public class CustomClass{
    @Autowired
    private ConfigurableApplicationContext configurableApplicationContext;

    public String evaluateExpression(String myString) {
        ConfigurableListableBeanFactory beanFactory =
              configurableApplicationContext.getBeanFactory();
          StringValueResolver str = new EmbeddedValueResolver(beanFactory);
          return str.resolveStringValue(myString);
          //Put Above statement in Try catch .. Worked for me
    }
}

It will work with Any of the environment variable Example


application.properties

data.myenv=10


/etc/profile

export DATA_MYENV=10