使用@ResponseStatus允许在Spring中设置Rest响应的状态。但是,如何将其用于可能来自同一请求的不同状态?

例如,控制器中有一个方法可能返回200或404。如何仅在一种方法中使用@ResponseStatus来定义这些状态?

分析解答

通常,您不会使用@ResponseStatus执行此操作。相反,您可以使用ResponseEntity<...>作为方法的返回类型。如果返回项目的“类型”可以更改,则ResponseEntity<?>ResponseEntity<Object>也可以工作。

例如:

@GetMapping("/{key}")
public ResponseEntity<Thing> getThing(final @PathVariable String key) {
    final Thing theThing = this.thingService.get(key);

    final ResponseEntity<?> response;
    if (theThing.someProperty()) {
         response = ResponseEntity.ok(theThing);
    } else {
         response = ResponseEntity.status(HttpStatus.NOT_MODIFIED).body(null);
    }

    return response;
}