使用Spring内部Spel Expression Parser

时间:2017-03-01 13:55:55

标签: spring spring-el

您是否知道如何使用Spring内部Spel Expression Parser来解析包含Spring Application Context的bean引用的String?

我已经看到SpelExpressionParser可以与定义某些显式用户变量的StandardEvaluationContext一起使用。

我正在寻找直接使用Spring内部Spel Expression Parser绑定到整个Spring Application Context的解决方案。我们的想法是使用具有@Value SPEL注释功能的字符串模板。

3 个答案:

答案 0 :(得分:0)

我使用以下方法找到了解决方案:

private Object resolveExpression(String expression) {
    String placeholdersResolved = applicationContext.getBeanFactory().resolveEmbeddedValue(expression);
    BeanExpressionResolver expressionResolver = applicationContext.getBeanFactory().getBeanExpressionResolver();
    return expressionResolver.evaluate(placeholdersResolved, new BeanExpressionContext(applicationContext.getBeanFactory(), null));
}

resolveEmbeddedValue将$ {}表达式替换为属性占位符。

使用Application Context Bean Factory评估resolve#{}表达式

答案 1 :(得分:0)

您可以使用EmbeddedValueResolver来获得与@Value注释相同的功能:

// can be autowired or fetched from ConfigurableApplicationContext.getBeanFactory()
ConfigurableBeanFactory configurableBeanFactory; 

EmbeddedValueResolver embeddedValueResolver = new EmbeddedValueResolver(configurableBeanFactory);
System.out.println(embeddedValueResolver.resolveStringValue("${someProperty}");
System.out.println(embeddedValueResolver.resolveStringValue("#{@foo.calcValue(123)}");

答案 2 :(得分:0)

public class CustomClass{
    @Autowired
    private ConfigurableApplicationContext configurableApplicationContext;

    public String evaluateExpression(String myString) {
        ConfigurableListableBeanFactory beanFactory =
              configurableApplicationContext.getBeanFactory();
          StringValueResolver str = new EmbeddedValueResolver(beanFactory);
          return str.resolveStringValue(myString);
          //Put Above statement in Try catch .. Worked for me
    }
}

它将与任何环境变量一起使用 例子


application.properties

data.myenv = 10


/ etc / profile

导出DATA_MYENV = 10