当前位置: 首页 > 知识库问答 >
问题:

使用Spring bean作为带有@cacheable注释的键

龙景澄
2023-03-14

代码如下所示。

@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'

共有1个答案

西门安民
2023-03-14

我检查了底层缓存解析实现,似乎没有一种简单的方法可以注入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);
    }

}
 类似资料:
  • 使用Spring bean作为带有@cacheable注释的键

  • 我写了一个示例Spring启动应用程序,它无法运行消息 `描述:com中的customerRepository字段。hibernatetutorial。服务CustomerServiceImpl需要“com”类型的bean。hibernatetutorial。存储库。找不到CustomerRepository“”。 操作:考虑在您的配置中定义类型为“com.hibernatetutorial.re

  • 我有一个用@Cacheable注释的方法。如果在方法内部捕获了异常,我希望清除缓存。但是,缓存似乎是在清除缓存的行之后执行的方面中加载的。因此,当在方法中捕获异常时,即使清除了缓存,空字符串结果仍保留在缓存中。 我应该从哪里清除缓存?

  • 我正在从下面的方法中获取电影列表,并带有@Cacheable注释。由于它没有任何参数,我将key设置为#root.method.name。 现在,我想添加一个新的电影,同样应该添加到上述缓存。 我试过这个,但它给了我例外。 我们可以在这里使用@CachePut注释,还是有其他方法?

  • 在Springs的最新版本中,我们可以使用注释作为自动连接bean。这将使用bean的类型(或构造函数,如果应用于它的话)自动连接bean。有什么方法可以使用基于bean名称的注释吗?我们在Spring的XML文件中没有注释autowire=“byName”?

  • 我的问题与另一个问题中的问题完全相同:“如何在自定义cxf拦截器中使用Spring Autowired?”。此处的有效响应建议通过上下文xml配置endpoint: 但我想完全不用xml配置,只通过注释来实现。是否可以通过注释@InInterceptors向@WebServiceendpoint添加拦截器(这是一个具有自动连接成员的Springbean)。还是有别的办法?