0 day streak
java / expert
Snippet

Global API Response Wrapping with ResponseBodyAdvice

ResponseBodyAdvice allows you to intercept and modify the response body after a controller method returns but before it is serialized. This is ideal for ensuring all API responses follow a consistent envelope structure.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
@RestControllerAdvice
public class UnifiedResponseWrapper implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if (body instanceof ApiResponse) return body;
return new ApiResponse<>(body, "Success", HttpStatus.OK.value());
}
}
spring
Breakdown
1
@RestControllerAdvice
Registers this component as a global interceptor for all REST controllers.
2
public boolean supports(...)
Determines which return types or controllers should be processed by this advice.
3
return new ApiResponse<>(body, ...);
Wraps the raw object into a standardized container before JSON serialization.