Программно оценивать выражение bean с помощью Spring Expression Language

У меня есть простое Spring Bean Expression, которое хорошо оценивается, когда я определяю его в файле контекста приложения:

<bean id="myConfigBean" class="com.example.myBeanConfigBean">
    <property name="myProperty" value="#{ someOtherBean.getData() }"/>
</bean>

Теперь я хочу сделать ту же оценку программно. Я использовал следующий код:

final ExpressionParser parser = new SpelExpressionParser();
final TemplateParserContext templateContext = new TemplateParserContext();
Expression expression = parser.parseExpression("#{ someOtherBean.getData() }", templateContext);
final String value = (String) expression.getValue();

Это создает исключение:

EL1007E:(pos 22): Field or property 'someOtherBean' cannot be found on null

Я предполагаю, что мне нужно как-то установить корневой объект, который позволяет настроенным bean-компонентам как свойству. Но я еще не заставил его работать. Кто-нибудь, кто уже сделал это и может дать подсказку?

2 ответа

Решение

Реализовать BeanFactoryAware, чтобы получить ссылку на фабрику бинов; затем...

StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new BeanFactoryResolver(this.beanFactory));
Expression expression = parser.parseExpression("@someOtherBean.getData()"); 
// or "@someOtherBean.data"
final String value = expression.getValue(context, String.class);

РЕДАКТИРОВАТЬ

Ответить на комментарий ниже. @ запускает использование обработчика фабрики компонентов для доступа к компоненту; альтернатива - добавить BeanExpressionContextAccessor в контексте оценки и использовать BeanExpressionContext как корневой объект для оценки...

final ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(new BeanFactoryResolver(beanFactory));
context.addPropertyAccessor(new BeanExpressionContextAccessor());
Expression expression = parser.parseExpression("someOtherBean.getData()");
BeanExpressionContext rootObject = new BeanExpressionContext(beanFactory, null);

...

String value = expression.getValue(context, rootObject, String.class);

Пожалуйста, посмотрите @ https://www.mkyong.com/spring3/test-spring-el-with-expressionparser/

Пример кода Java

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class App {
    public static void main(String[] args) {

        ExpressionParser parser = new SpelExpressionParser();

        //literal expressions
        Expression exp = parser.parseExpression("'Hello World'");
        String msg1 = exp.getValue(String.class);
        System.out.println(msg1);

        //method invocation
        Expression exp2 = parser.parseExpression("'Hello World'.length()");
        int msg2 = (Integer) exp2.getValue();
        System.out.println(msg2);

        //Mathematical operators
        Expression exp3 = parser.parseExpression("100 * 2");
        int msg3 = (Integer) exp3.getValue();
        System.out.println(msg3);

        //create an item object
        Item item = new Item("mkyong", 100);
        //test EL with item object
        StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

        //display the value of item.name property
        Expression exp4 = parser.parseExpression("name");
        String msg4 = exp4.getValue(itemContext, String.class);
        System.out.println(msg4);

        //test if item.name == 'mkyong'
        Expression exp5 = parser.parseExpression("name == 'mkyong'");
        boolean msg5 = exp5.getValue(itemContext, Boolean.class);
        System.out.println(msg5);

    }
}
Другие вопросы по тегам