【发布时间】:2015-11-16 16:14:51
【问题描述】:
我已经为此工作了几天,正在寻找解决方案,但我被卡住了。
这与其他已回答的问题类似: Programmatically evaluate a bean expression with Spring Expression Language
在我的 java 应用程序(命令行,而不是 Web)中,我使用 Spring 来连接应用程序类。在我的applicationContext.xml 我有这个
<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:config/#{systemProperties['ENV']?:'LOCAL'}.properties"/>
</bean>
这很好用。 在我的应用程序中,我想评估类似的字符串,并且我开发了这种方法
@Component("myAppAware ")
public class MyAppAware implements BeanFactoryAware {
@Autowired
private ApplicationContext applicationContext;
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; }
public String process(){
String toParse = "classpath:config/#{systemProperties['ENV']?:'LOCAL'}.properties";
BeanFactoryResolver beanFactoryResolver = new BeanFactoryResolver(beanFactory);
StandardEvaluationContext context = new StandardEvaluationContext();
context.setBeanResolver(beanFactoryResolver);
SpelExpressionParser parser = new SpelExpressionParser();
TemplateParserContext templateContext = new TemplateParserContext();
Expression expression = parser.parseExpression(toParse,templateContext);
Object ovalue = expression.getValue(context); // EXCEPTION THROWN HERE !!!
String value = ovalue.toString();
return value;
}
但是当我运行这段代码时,会抛出一个错误
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'systemProperties' cannot be found on null
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:243)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:112)
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:107)
我想我已经接近我的目标了,但我不知道如何将应用程序上下文 bean 放入解析器,或者如何让它工作 有人可以帮忙吗?
【问题讨论】:
-
您使用的是哪个 Spring 版本?另外,你能不试试
TemplateParserContext,比如new SpelExpressionParser().parseExpression(toParse).getValue()吗? -
在解析EL表达式时尝试构造目标。
-
没有
TemplateParserContext,#{ }不起作用。 -
我的Spring版本是3.2.4,谢谢
-
解析EL表达式时如何构造目标?