使用Spring Bean作为具有@Cacheable批注的键 [英] Using Spring beans as a key with @Cacheable annotation

查看:107
本文介绍了使用Spring Bean作为具有@Cacheable批注的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进行以下工作: -一个具有应使用@Cacheable批注缓存的方法的spring bean -另一个为缓存创建密钥的Spring bean(KeyCreatorBean).

How to make following to work: - a spring bean that has a method that should be cached with @Cacheable annotation - another spring bean that creates keys for the cache (KeyCreatorBean).

所以代码看起来像这样.

So the code looks something like this.

@Inject
private KeyCreatorBean keyCreatorBean;

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

但是上面的代码不起作用:它给出了以下异常:

However the above code doesn't work: it gives following exception:

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之类的表达式.

I checked the underlying cache resolution implementation, there doesn't appear to be a simple way to inject in a BeanResolver which is required for resolving the beans and evaluating expressions like @beanname.method.

因此,我也将按照@micfra推荐的方式,推荐一种不太讲究的方法.

So I would also recommend a somewhat hacky way along the lines of one which @micfra has recommended.

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

Along what he has said, have a KeyCreatorBean along these lines, but internally delegate it to the keycreatorBean that you registered in your application:

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);
    }

}

这篇关于使用Spring Bean作为具有@Cacheable批注的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆