Implementing a cache allows us to save data temporally in the memory to be used later in subsequent requests requiring the same data without additional requests to an external service or a database.

Sometimes a requirement needs a specific implementation of the caching mechanism. In this case, I will describe how to implement a cache that spring will discard once the service has processed the request.  


Add the dependencies

Ensure that you have included the spring cache abstraction in your 'pom.xml'

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

Enable caching in the main class

We have to specify that our application now will use the spring boot cache capabilities by adding the '@EnableCaching' annotation to our main class.

@SpringBootApplication
@EnableCaching
public class CachingApplication {

	public static void main(String[] args) {
		SpringApplication.run(CachingApplication.class, args);
	}

}

Add the @Caching annotation to your method.

Notice that I'm specifying a cache manager. I have to define that cache manager that will be my Request Scoped bean.

@Service
public class GameServiceImpl implements GameService{

    private GameDAO gameDAO;

    @Autowired
    public GameServiceImpl(GameDAO gameDAO) {
        this.gameDAO = gameDAO;
    }
    
    ...
    
    @Override
    @Cacheable(cacheNames = "gameList", cacheManager = "gameCacheManager")
    public List<Game> getAllGames() {
        return gameDAO.findAll();
    }


}

Declare the cache manager

Define a method that will return a CacheManager object. This method will have the @Bean annotation with the same name as we specified in the cacheManager from the @Cacheable annotation; we also have to add the @RequestScope annotation to spring need to discard this bean once the request is complete.

@Bean(name = "gameCacheManager")
    @RequestScope(proxyMode = ScopedProxyMode.TARGET_CLASS)
    public CacheManager getCacheManager(){
        return new ConcurrentMapCacheManager();
    }

And now we have a Request Scoped cache that spring will discard once the current request is complete.

This is useful when you depend on an external service that constantly updates its data or when the returned data by the external service is big enough to be a memory concern.