Search code examples
javarestspring-boothttp-headersresttemplate

SpringBoot – add Cache Control Headers in Rest methods


I have a basic SpringBoot 2.0.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR

I have created this Rest method:

  @GetMapping(path = "/users/notifications", consumes = "application/json", produces = "application/json")
    public ResponseEntity<List<UserNotification>> userNotifications(
            @RequestHeader(value = "Authorization") String authHeader) {

        User user = authUserOnPath("/users/notifications", authHeader);

        List<UserNotification> menuAlertNotifications = menuService
                .getLast365DaysNotificationsByUser(user);

        return ResponseEntity.ok(menuAlertNotifications)
                .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS));;

    }

and I want to add a Cache Control Headers, but I don't know how... I got a compilation error:

Multiple markers at this line
    - The method cacheControl(CacheControl) is undefined for the type 
     ResponseEntity<List<UserNotification>>
    - CacheControl
    - cacheControl

I also add this property in application.properties

security.headers.cache=false


Solution

  • When you use ResponseEntity.ok(T body) the return type is ResponseEntity<T> as it is a shortcut method to add data to the body part of the ResponseEntity.

    You need the builder object that is created via ResponseEntity.ok() with no param which returns a Builder object. You then add your data yourself on via the body method.

    So your code should be like this

      @GetMapping(path = "/users/notifications", consumes = "application/json", produces = "application/json")
        public ResponseEntity<List<UserNotification>> userNotifications(
                @RequestHeader(value = "Authorization") String authHeader) {
    
            User user = authUserOnPath("/users/notifications", authHeader);
    
            List<UserNotification> menuAlertNotifications = menuService
                    .getLast365DaysNotificationsByUser(user);
    
    
            return ResponseEntity.ok().cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)).body(menuAlertNotifications);
    
    
        }