Elegant Backend API Design: Automatic Response Wrapping with Spring ResponseBodyAdvice
This article demonstrates how to design elegant backend API responses using a standardized JSON format with categorized status codes, then implements automatic response wrapping via Spring's ResponseBodyAdvice and a custom @ResponseResult annotation to eliminate boilerplate code in controllers while maintaining clean business logic.
Reading font

API Response Format Design
The article begins by establishing a standard JSON response structure for frontend-backend communication:
{
code: integer, // Return status code
message: string, // Return message description
data: object // Return value
}Status Code Categorization
Instead of adding status codes ad-hoc during development (e.g., 101 for permission error, 102 for parameter error), the author recommends organizing codes into ranges inspired by HTTP status codes:
1000–1999 : Parameter errors
2000–2999 : User errors
3000–3999 : Interface exceptions
This allows frontend developers to quickly identify error categories from the code range, then use the message field for specific details.
Message and Data Design
The message field provides human-readable error descriptions, typically defined alongside status codes in an enum for maintainability. The data field holds the business payload as a JSON object, varying per endpoint.
Initial Controller Implementation
A generic Result<T> wrapper class is introduced. In a typical controller, the business object is manually wrapped:
@GetMapping("/order/{id}")
public Result<Order> getOrder(@PathVariable Long id) {
Order order = orderService.getOrder(id);
return new Result<>(200, "success", order);
}First Optimization: Static Factory Methods
To reduce verbosity, static methods are added to Result:
public static <T> Result<T> success(T data) {
return new Result<>(200, "success", data);
}
public static <T> Result<T> failure(int code, String msg) {
return new Result<>(code, msg, null);
}Controller code becomes:
return Result.success(order);Problems with Static Factory Approach
The author identifies three issues:
Every method returns Result, losing business semantics in the signature.
Repetitive Result.success() / Result.failure() calls clutter business logic.
Manual null checks (e.g., if (id == null)) duplicate validation that could be handled by Hibernate Validator.
Elegant Solution: Automatic Wrapping with Spring AOP
The goal: controllers return plain domain objects (e.g., Order), and a framework layer automatically wraps successful responses and exceptions into the standard Result format.
Implementation Steps
Custom annotation @ResponseResult — marks methods or classes whose return values need wrapping.
HandlerInterceptor — inspects the handler method for @ResponseResult and sets a request attribute flag.
ResponseBodyAdvice + @ControllerAdvice — implements supports() to check the flag and beforeBodyWrite() to wrap the return value into Result.
Annotation Definition
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ResponseResult {}Interceptor
public class ResponseResultInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod) handler;
ResponseResult ann = hm.getMethodAnnotation(ResponseResult.class);
if (ann == null) {
ann = hm.getBeanType().getAnnotation(ResponseResult.class);
}
if (ann != null) {
request.setAttribute(RESPONSE_RESULT_ANN, ann);
}
}
return true;
}
}ResponseBodyAdvice Implementation
@ControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType,
Class<? extends HttpMessageConverter<?>> converterType) {
// Check request attribute set by interceptor
return RequestContextHolder.getRequestAttributes()
.getAttribute(RESPONSE_RESULT_ANN, RequestAttributes.SCOPE_REQUEST) != null;
}
@Override
public Object beforeBodyWrite(Object body,
MethodParameter returnType,
MediaType selectedContentType,
Class<? extends HttpMessageConverter<?>> selectedConverterType,
ServerHttpRequest request,
ServerHttpResponse response) {
if (body instanceof Result) return body; // Already wrapped
if (body instanceof Throwable) {
// Exception handling omitted for brevity
return Result.failure(500, body.getMessage());
}
return Result.success(body);
}
}Usage
Annotate the controller class or individual methods:
@RestController
@ResponseResult
public class OrderController {
@GetMapping("/order/{id}")
public Order getOrder(@PathVariable @NotNull Long id) {
return orderService.getOrder(id);
}
}Now the controller returns the raw Order object; validation is handled by @NotNull (Hibernate Validator), and the advice wraps the response automatically.
Exception Handling Note
The article mentions that global exception handling (e.g., @ExceptionHandler) can be combined with this approach but is omitted for brevity.
Performance Optimization
The interceptor reflects on the handler method on every request. The author suggests caching the @ResponseResult presence per method to avoid repeated reflection.
About this article
For attribution, corrections or content rights, contact