Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Spring internal Spel Expression Parser

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.

like image 544
user3849838 Avatar asked Aug 13 '26 01:08

user3849838


2 Answers

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)}");
like image 98
Marat Buharov Avatar answered Aug 14 '26 16:08

Marat Buharov


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

like image 34
user3849838 Avatar answered Aug 14 '26 15:08

user3849838



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!