我正在尝试替换旧的:
@Component
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {
@QueryHints({@QueryHint(name = CACHEABLE, value = "true")})
MyEntity findByName(String name);
}
由此:
@Component
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {
@Cacheable(value = "entities")
MyEntity findByName(String name);
}
因为我想使用高级缓存功能,比如没有缓存空值等等。
为此,我遵循了Spring教程https://spring.io/guides/gs/caching/
如果我没有注释我的Application.java,则缓存根本不起作用。
但是如果我添加@EnableCaching
和CacheManager bean:
package my.application.config;
@EnableWebMvc
@ComponentScan(basePackages = {"my.application"})
@Configuration
@EnableCaching
public class Application extends WebMvcConfigurerAdapter {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("entities");
}
// ...
}
启动时出现以下错误:
java.lang.IllegalStateException:未指定CacheResolver,并且找不到CacheManager类型的bean。注册CacheManager bean或从配置中删除@EnableCaching注释
如果我用CacheResolver bean替换My CacheManager bean,我会得到同样的错误:
@Bean
public CacheResolver cacheResolver() {
return new SimpleCacheResolver(new ConcurrentMapCacheManager("entities"));
}
我错过了什么吗?
答案 0 :(得分:12)
@herau你是对的我必须给这个豆命名! 问题是还有另一个bean&#34; cacheManager&#34;,所以最后,我没有注释Application,并创建了一个配置:
@EnableCaching
@Configuration
public class CacheConf{
@Bean(name = "springCM")
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("entities");
}
}
MyEntityRepository
中的:
@Cacheable(value = "entities", cacheManager = "springCM")
MyEntity findByName(String name);
答案 1 :(得分:0)
就我而言,Spring Boot库很旧,无法轻松升级。因此,我使用了EHCache 2版本,并且可以在我的应用程序中使用。这是我发现对您有用的项目:https://github.com/TechPrimers/spring-ehcache-example/blob/master/src/main/resources/ehcache.xml