使用Springbeans作为带有@Cacheable注释的键



如何使以下内容发挥作用:-一个springbean,它有一个应该使用@Cacheable注释缓存的方法-另一个为缓存创建键的springbean(KeyCreatorBean)。

所以代码看起来像这样。

@Inject
private KeyCreatorBean keyCreatorBean;
@Cacheable(value = "cacheName", key = "{@keyCreatorBean.createKey, #p0}")
@Override
public List<Examples> getExamples(ExampleId exampleId) {
  ...

然而,上面的代码不起作用:它给出了以下异常:

Caused by: org.springframework.expression.spel.SpelEvaluationException: 
    EL1057E:(pos 2): No bean resolver registered in the context to resolve access to bean 'keyCreatorBean'

我检查了底层缓存解析实现,似乎没有一种简单的方法来注入BeanResolver,这是解析bean和计算@beanname.method等表达式所必需的。

因此,我也建议采用@micfra推荐的方法。

按照他所说的,有一个KeyCreatorBean,但在内部将其委托给您在应用程序中注册的KeyCreatorBean:

package pkg.beans;
import org.springframework.stereotype.Repository;
public class KeyCreatorBean  implements ApplicationContextAware{
    private static ApplicationContext aCtx;
    public void setApplicationContext(ApplicationContext aCtx){
        KeyCreatorBean.aCtx = aCtx;
    }

    public static Object createKey(Object target, Method method, Object... params) {
        //store the bean somewhere..showing it like this purely to demonstrate..
        return aCtx.getBean("keyCreatorBean").createKey(target, method, params);
    }
}

如果您有一个静态类函数,它将像一样工作

@Cacheable(value = "cacheName", key = "T(pkg.beans.KeyCreatorBean).createKey(#p0)")
@Override
public List<Examples> getExamples(ExampleId exampleId) {
  ...
}

带有

package pkg.beans;
import org.springframework.stereotype.Repository;
public class KeyCreatorBean  {
    public static Object createKey(Object o) {
        return Integer.valueOf((o != null) ? o.hashCode() : 53);
    }
}

最新更新