Spring REST:为特殊返回值创建自定义响应



我想添加一个横切策略,将Spring @RestController方法的某些返回类型转换为另一个响应实体。

鉴于,我有一个界面

interface AsyncResult<T> {
  public CompletableFuture<T> getResult();
}

我想写

@RequestMapping(...)
public AsyncResult getAsyncResult() { return ... }

并在某种策略中创建实际响应,例如

public ResponseEntity convert(AsyncResult result) { 
  if(result.getResult().isDone()) {
    return new ResponseEntity(result.get(), HttpStatus.OK);
  } else {
    // headers e.g. AsyncResult: true, Poll-Location: /result/result-id
    return new ResponseEntity(HttpStatus.ACCEPT, headers);
  }
}

我想这是可以通过注册类似于@ExceptionHandler的东西来实现的?

看起来答案是实现一个org.springframework.web.method.support.HandlerMethodReturnValueHandler

最新更新