4
  • Can i use Spring caching annotations on top of methods in a RestController.
  • As spring caching is a service level cache but i have a case there is no service so i'm using caching in controller.
  • Is it good to use caching in controller.
  • I'm using cafeine as my underlying cache.
  • I'm thinking that any multithreading issues may happen by using like this caching in controller level.
sreedhar
  • 296
  • 1
  • 5
  • 15
  • why not extract whatever you are trying to cache out to a service layer? You shouldn't really be mixing these layers within Spring as it just adds needless complexity. – Darren Forsythe Aug 17 '17 at 09:16

1 Answers1

4

I wouldn't use cacheable("something") in a spring controller that involves user authentication as the cacheable is only keeping arguments. However I do not see any problem if you do not need to cache depending on the user or any request header information.

For example, in the following example, when you are getting the user logged back:

        @RequestMapping(...)
        @Cacheable("something")
        public T analyze(@RequestParam(value = "text") String text) {
        ....
           Object userObj = 
       SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        ....
        }

An option you might have in case you want to cache depending on the header is to add @RequestHeader(value="key") String val in the controller method

kimy82
  • 4,069
  • 1
  • 22
  • 25