SpringBoot –在Rest方法中添加缓存控制头

时间:2018-10-15 06:47:22

标签: java rest spring-boot http-headers resttemplate

我有一个基本的SpringBoot 2.0.5.RELEASE应用程序。使用Spring Initializer,JPA,嵌入式Tomcat,Thymeleaf模板引擎并将其打包为可执行JAR

我创建了这个Rest方法:

  @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));;

    }

,我想添加一个缓存控制标头,但我不知道如何... 我遇到了编译错误:

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

我还在application.properties

中添加了此属性

security.headers.cache = false

1 个答案:

答案 0 :(得分:1)

使用ResponseEntity.ok(T body)时,返回类型为ResponseEntity<T>,这是将数据添加到ResponseEntity正文部分的快捷方法。

您需要通过ResponseEntity.ok()创建的没有参数的构建器对象,该参数将返回Builder对象。然后,您可以通过body方法自己添加数据。

所以您的代码应该像这样

  @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);


    }