Jac*_*ack 11 java spring spring-el
我有一个简单的Spring Bean Expression,当我在应用程序上下文文件中定义它时,它会很好地评估:
<bean id="myConfigBean" class="com.example.myBeanConfigBean">
<property name="myProperty" value="#{ someOtherBean.getData() }"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
现在,我想以编程方式进行相同的评估.我使用了以下代码:
final ExpressionParser parser = new SpelExpressionParser();
final TemplateParserContext templateContext = new TemplateParserContext();
Expression expression = parser.parseExpression("#{ someOtherBean.getData() }", templateContext);
final String value = (String) expression.getValue();
Run Code Online (Sandbox Code Playgroud)
这引发了一个异常:
EL1007E:(pos 22): Field or property 'someOtherBean' cannot be found on null
Run Code Online (Sandbox Code Playgroud)
我想我必须以某种方式设置一个根对象,允许配置的bean像属性一样.但我还没有让它工作.任何人,已经做过这个并且可以给出一个提示吗?
Gar*_*ell 12
实现BeanFactoryAware以获取对bean工厂的引用; 然后...
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);
Run Code Online (Sandbox Code Playgroud)
编辑
回答下面的评论.该@触发器使用bean工厂解析器来访问一个bean; 另一种方法是BeanExpressionContextAccessor在评估上下文中添加一个并使用a 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12959 次 |
| 最近记录: |