使用Spring EL和应用程序上下文bean评估bean表达式

时间:2015-11-16 16:14:51

标签: java spring spring-el

我已经在这几天工作,寻找解决方案,但我被卡住了。

这与其他回答的问题类似: 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添加到解析器中,或者如何使其工作 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

这应该有效:

String toParse = "classpath:config/#{@systemProperties['ENV']?:'LOCAL'}.properties"; 

如果你真的有systemProperties豆......

使用XML定义它有点不同,因为它基于StandardBeanExpressionResolver。但是从目标应用程序中使用起来有点复杂。

<强>更新

this.expressionContext = (beanFactory != null ? new BeanExpressionContext(beanFactory, null) : null);
 ...............
private Object resolveDefaultValue(String defaultValue) {
    if (this.configurableBeanFactory == null) {
        return defaultValue;
    }
    String placeholdersResolved = this.configurableBeanFactory.resolveEmbeddedValue(defaultValue);
    BeanExpressionResolver exprResolver = this.configurableBeanFactory.getBeanExpressionResolver();
    if (exprResolver == null) {
        return defaultValue;
    }
    return exprResolver.evaluate(placeholdersResolved, this.expressionContext);
}

请参阅AbstractNamedValueMethodArgumentResolver源代码。