Оцените выражение bean-компонента с помощью Spring EL с помощью bean-компонента контекста приложения

Я работал над этим несколько дней, в поисках решения, но я застрял.

Это похоже на другой ответ на вопрос: программно оценивать выражение bean-компонента с помощью Spring Expression Language

В моем Java-приложении (командная строка, а не в Интернете) я использую 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) 

Я думаю, что я близок к своей цели, но я не знаю, как получить компоненты контекста приложения в парсер, или как заставить его работать, кто-нибудь может помочь?

1 ответ

Это должно работать:

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 исходный код.

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