Understanding @Enable... annotations concurrency

129 Views Asked by At

We have a project that uses spring-boot-cache-starter, registering an ehCache CacheManager implementation, and spreading @Cacheables accross the code.

Then, some other team created an starter, that basically relies on the default configuration autconfigured by spring-boot-cache starter (hashmap) for its own processing of @Cacheable methods.

Both codes contain the @EnableCaching annotation, and our issue is that the behavior is different in case we comment our main project's @EnableCaching annotation.

  1. If we don't comment @EnableCaching in our project, when we use the custom starter, everything works fine. @Cacheables from the starter are indexed and resolved in the starter scope but @Cacheables from our domain are resolved in our ehcache.
  2. If we comment @EnableCaching in our project, then both the starter and our project's @Cacheables are tried to be resolved against our ehCache implementation.

This breaks a lot of preconceptions I had so far:

  1. I always thought an annotation such as @Enable... applied to all the context, regardless of the placement (starter/application configuration), and regardless of whether it was found once or twice when scanning all @Configuration classes.

  2. Why does the case work when both annotations are there, I guess the CacheManager in the spring-boot-cache-starter is a @ConditionalOnBean, so in that case I would expect both projects using the ehcache bean for resolving, not each one's domain

P.S: the @EnableCaching found in our main project is placed on an inner static @Configuration class. Could this be significant?

1

There are 1 best solutions below

0
On

It is very hard to answer your question if you don't reveal what the custom starter does. In particular, this looks weird to me:

@Cacheables from the starter are indexed and resolved in the starter scope but @Cacheables from our domain are resolved in our ehcache.

Your preconceptions 1 is valid: it doesn't matter where you you put the annotation or if you add it more than once. It will just enable caching for the whole ApplicationContext. In the case of Spring Boot, that will trigger the auto-configuration unless a custom CacheManager bean is defined in user's configuration.

The "each one's domain" sounds broken to me. Are you sure this is what's happening? If you want to store in several cache managers there is not a lot of different ways:

  1. You need to define a CacheResolver and refer to it in the @Cacheable annotations (or @CacheConfig)
  2. You need a special CacheManager that knows where to find the caches in each underlying stores

If each domain has a standard use of @Cacheable it will go against the CacheManager. If you notice the behaviour you are describing, it has nothing to do with @EnableCaching at all.