java - Spring 注入(inject) Guava 缓存

标签 java spring inversion-of-control guava

出于某种原因,我无法构建 Guava 缓存实例并将其作为 Spring bean 公开。

构造代码如下:

@Configuration
public class ProductRepositoryCache {

    @Bean
    public Cache<NameSearchKey,Collection<String>> nameSearchCache() {
        Cache<NameSearchKey,Collection<String>> result = CacheBuilder.newBuilder()
                .maximumSize(1024)
                .expireAfterAccess(0, TimeUnit.HOURS)
                .expireAfterWrite(6, TimeUnit.HOURS)
                .build();
        return  (Cache<NameSearchKey,Collection<String>>) result;
    }
}

然后使用它:

@Resource
Cache<NameSearchKey,Collection<String>> nameSearchCache;

但部署失败:

Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'nameSearchCache' must be of type [com.google.common.cache.Cache], but was actually of type [com.google.common.cache.CacheBuilder]|#]

我相信我遗漏了一些简单的东西,但找不到它。所以,我的问题是 - 我做错了什么?

最佳答案

真正的返回实例是 com.google.common.cache.LocalCache.LocalManualCache 这是一个缓存。我认为你的代码是正确的,而且我之前也做过同样的事情,它工作正常。

我建议检查包含以下内容的 BeanNotOfRequiredTypeException:

beanName - the name of the bean requested

requiredType - the required

type actualType - the actual type returned, which did not match the expected type

然后您可以调试 BeanNotOfRequiredTypeException 实例以找出原因。

另外,你可以显式声明Bean名称,这样可以避免一些容易出错的情况。

@Bean(name = "thisCache")
public Cache<NameSearchKey,Collection<String>> nameSearchCache() {...}

@Resource(name = "thisCache")
Cache<NameSearchKey,Collection<String>> nameSearchCache;

关于java - Spring 注入(inject) Guava 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11817845/

相关文章:

Java - 如何创建子字符串直到到达非数字字符?

java - 不同的测试方法使用不同的Spring测试上下文配置

java - Spring MVC - 当整数值为零时如何显示空白文本框

c# - 将依赖项注入(inject)动态加载的 .dll (.net core)

dependency-injection - Autofac OwnedInstances 和 ASP.NET Web API 的 InstancePerApiRequest 支持

c# - 使用ctor注入(inject)和ServiceProvider创建实例

java - 使用递归将多项式相加

java - Image Servlet 还可以访问其他文件

java - (初学者) JAVA do...while 循环逻辑坏了?

java - Spring表单未提交