在 spring boot 应用程序中实例化 CacheManager bean

问题描述 投票:0回答:1

我在用

@Service
public class Service{
@Autowired  
private CacheManager cacheManager;
}  

我在 build.gradle 文件中包含了 org.ehcache:ehcache 和 spring-boot-starter-cache 库。 在运行应用程序时出现错误:

Field cacheManager required a bean of type org.springframework.cache.CacheManager that could not be found.

我不确定如何解决这个错误

我的想法:
看起来我需要声明一个用@Configuration 和@Bean 方法注释的类,它返回一个CacheManager 类型的对象。我在这里使用 EhCache。不确定到底该怎么做。

java spring-boot spring-cache ehcache-3
1个回答
0
投票

我相信@dey是正确的。

我怀疑您遇到的问题是您没有使用 Spring Framework 的

@EnableCaching
注释(Javadoc)显式启用缓存。

即使使用 Spring Boot 的自动配置,特别是在使用 Ehcache 作为 Spring Framework 的缓存抽象中的缓存提供程序时,您仍然需要显式启用缓存,如 文档中所述

Ehcache 是一个支持的缓存提供程序(以及在核心 Spring Framework 中)并且 Spring Boot 确实为该提供程序提供自动配置逻辑(通过 JCache API)。但是,当使用 Spring Boot 时,应用程序配置中的显式

CacheManager
bean 声明(对于 Ehcache)是 not 需要的,只需要
@EnableCaching
注释(只要 Ehcache
spring-boot-starter-cache
正如您所指出的,在您的应用程序类路径中):

@Configuration
@EnableCaching
class MySpringBootApplicationConfiguration {

  // your application managed bean declarations here

}

仅当 1) 您不使用 Spring Boot,或 2) Spring 不(提供)支持提供程序作为 Spring 缓存抽象中的缓存提供程序时,才需要显式

CacheManager
bean,在这种情况下,您需要实现 Spring 的
Cache and 
CacheManager` SPI 自己,用于不受支持的 (OOTB) 提供者。

© www.soinside.com 2019 - 2024. All rights reserved.