7

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.

0

3 Answers 3

2

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)}");
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.