javaspringspring-bootcachingconfiguration

SpringBoot @Cacheable with @Bean usage


I stumbled upon a code where @Cacheable annotation is used with @Bean and the class was annotated with @Configuration

for example

@Configuration
public class CacheManager {

  @Cacheable("urls")
  @Bean
  public Map<String,String> loadUrl(){
   // hashmap population logic
   return urlMap;
  }


}

Does this load all the caches at configuration phase ? Or the @Cacheable annotation will be ignored

Chatgpt says

This won't work — @Cacheable will be ignored. That's because Spring creates the bean during the configuration phase, and at that point caching proxies are not yet applied.


Solution

  • It will not work.
    You have the default bean scope - singleton. It means that the bean creates once.

    So loadUrl will be executed on the application's startup.
    Later, when you call loadUrl again, loadUrl will not be executed — loadUrl will return the initial value instead.
    Even after the expiration timeout that you set in cacheManager, when you call loadUrl again, loadUrl will not be executed.

    You can test this:

    If you want make @Cacheable to work as expected, then change the scope to prototype - @Scope("prototype").

    But I would say, that it is strange approach.
    Usually the @Cacheable annotation is placed on public methods of services or components.