简体   繁体   中英

Injecting guava cache in spring

For some reason i'm not able to construct a guava cache instance and expose it as a Spring bean.

Here is the construction code:

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

and then use it:

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

but deployment fails with:

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]|#]

I believe i'm missing something simple, but can't find it. So, my question is - what i'm doing wrong?

The real return instance is com.google.common.cache.LocalCache.LocalManualCache which is a Cache. your code is correct I think, moreover I did the same thing before, it works fine.

I suggest to check the BeanNotOfRequiredTypeException which contains:

beanName - the name of the bean requested

requiredType - the required

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

then you could debug for the BeanNotOfRequiredTypeException instance to find the cause.

Also, you could declare Bean explicit name, it can avoid some error prone.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM