【问题标题】:Spring 4 @Cacheable unless expression with property expressionSpring 4 @Cacheable 除非带有属性表达式的表达式
【发布时间】:2018-11-05 03:02:46
【问题描述】:

是否可以在@Cacheable注解的unless表达式中使用spring属性占位符?我有一个想要缓存的服务方法,除非返回的结果小于 @PropertySource("classpath:application.properties") 中指定的属性 minCacheCalc 的值。

这里是我要缓存的服务类方法:

@Service
class CalculationService {
    // @Cacheable(cacheNames="calculations", unless="#result < 10") // works fine hardcoded
    @Cacheable(cacheNames="calculations", unless="#result < ${minCacheCalc}")
    public Integer calculate(Integer i) {
        System.out.println("calculate(" + i + ")");
        return i * i - i;
    }

}

调用这个会抛出错误:

SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

我尝试了许多不同的语法,但似乎找不到。

有没有办法在我的@Cacheable 的unless 参数中引用属性?

【问题讨论】:

标签: java spring spring-el


【解决方案1】:

我觉得应该更像:

#{result lt minCacheCalc}

我用this as a reference

【讨论】:

    【解决方案2】:

    你可以这样实现:

    • 在类的字段中注入属性值
    private int minCacheCalc;
    
    public CalculationService(@Value("${minCacheCalc}") int minCacheCalc) {
        this.minCacheCalc = minCacheCalc;
    }
    
    
    • 添加属性的getter
    public int getMinCacheCalc() {
        return this.minCacheCalc;
    }
    
    • 在 unless SpEL 中使用实例字段
    @Cacheable(cacheNames="calculations", unless="#result < #root.target.minCacheCalc")
    

    【讨论】:

      猜你喜欢
      • 2012-12-08
      • 2021-07-14
      • 2012-05-10
      • 1970-01-01
      • 2011-07-27
      • 2017-05-19
      • 2017-07-26
      • 1970-01-01
      • 2012-04-21
      相关资源
      最近更新 更多