使用Spring表达式语言以编程方式评估Bean表达式 [英] Programmatically evaluate a bean expression with Spring Expression Language

查看:216
本文介绍了使用Spring表达式语言以编程方式评估Bean表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Spring Bean表达式,当我在应用程序上下文文件中定义它时,它的计算效果很好:

I have a simple Spring Bean Expression, which evaluates fine when I define it inside an application context file:

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

现在,我想以编程方式进行相同的评估.我使用了以下代码:

Now, I want to do the same evaluation programmatically. I have used the following code:

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.但是我还没有开始工作.任何人都已经这样做并且可以给出提示了吗?

I guess I have to set a root object somehow that allows to the configured beans like a property. But I did not get it to work yet. Anyone, who has done this already and could give a hint?

推荐答案

实现BeanFactoryAware以获得对bean工厂的引用;然后...

implement BeanFactoryAware to get a reference to the bean factory; then...

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);

编辑

要回答以下评论. @触发使用bean工厂解析器访问bean.另一种方法是在评估上下文中添加BeanExpressionContextAccessor,并使用BeanExpressionContext作为评估的根对象...

To answer the comment below. The @ triggers the use of the bean factory resolver to access a bean; an alternative is to add a BeanExpressionContextAccessor to the evaluation context and use a BeanExpressionContext as the root object for the evaluation...

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);

这篇关于使用Spring表达式语言以编程方式评估Bean表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆