Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use Spring @Cacheable and @EnableCaching

I'm trying to replace my old:

@Component
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {

    @QueryHints({@QueryHint(name = CACHEABLE, value = "true")})
    MyEntity findByName(String name);
}

by this:

@Component
public interface MyEntityRepository extends JpaRepository<MyEntity, Integer> {

    @Cacheable(value = "entities")
    MyEntity findByName(String name);
}

Because I want to use advanced caching features like no caching of null values, etc.

To do so, I followed Spring tutorial https://spring.io/guides/gs/caching/

If I don't annotate my Application.java, caching simply doesn't work.

But if I add @EnableCaching and a 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");
    }

// ...
}

I get the following error at startup:

java.lang.IllegalStateException: No CacheResolver specified, and no bean of type CacheManager found. Register a CacheManager bean or remove the @EnableCaching annotation from your configuration

I get the same error if I replace My CacheManager bean by a CacheResolver bean like:

@Bean
public CacheResolver cacheResolver() {
    return new SimpleCacheResolver(new ConcurrentMapCacheManager("entities"));
}

Do I miss something ?

like image 599
Pleymor Avatar asked Sep 01 '15 06:09

Pleymor


1 Answers

@herau You were right I had to name the bean ! The problem was that there were another bean "cacheManager", so finally, I didn't annotate Application, and created a configuration as:

@EnableCaching
@Configuration
public class CacheConf{
    @Bean(name = "springCM")
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("entities");
    }
}

in MyEntityRepository:

    @Cacheable(value = "entities", cacheManager = "springCM")
    MyEntity findByName(String name);
like image 121
Pleymor Avatar answered Sep 19 '22 05:09

Pleymor