我有一个基本的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
答案 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);
}