就在这里! (如果您使用的是4.1或更高版本的弹簧).
它被称为ResponseBodyAdvice,它使您能够拦截调用(就在写入响应之前,并提供对原始http响应的访问).
基本上你需要的是实现这样的控制器建议:
@ControllerAdvice
public class ResourceSizeAdvice implements ResponseBodyAdvice> {
@Override
public boolean supports(MethodParameter returnType, Class extends HttpMessageConverter>> converterType) {
//Checks if this advice is applicable.
//In this case it applies to any endpoint which returns a collection.
return Collection.class.isAssignableFrom(returnType.getParameterType());
}
@Override
public Collection> beforeBodyWrite(Collection> body, MethodParameter returnType, MediaType selectedContentType, Class extends HttpMessageConverter>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
response.getHeaders().add("X-Total-Count", String.valueOf(body.size()));
return body;
}
}