出于某种原因,我无法构建 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/