Designing Unified API Response Wrappers with @ResponseResult in Spring
This article explains how to design a consistent JSON response structure for Spring-based micro‑service APIs, introduces a Result wrapper class, demonstrates annotation‑driven response handling, and shows controller, interceptor, and advice implementations to produce clean, maintainable backend responses.
In modern micro‑service architectures, APIs usually return JSON payloads that contain a status code, a message, and a data object. The article proposes a unified response format:
{
// return status code
code: integer,
// description message
message: string,
// actual payload
data: object
}It suggests aligning custom codes with HTTP status semantics and optionally using a four‑digit scheme (e.g., 1000‑1999 for parameter errors, 2000‑2999 for user errors, 3000‑3999 for interface exceptions) to make error classification easier.
The Result class is introduced as a wrapper that can be instantiated via static helper methods such as Result.success(data) or Result.failure(code, message) , improving readability in controller code.
To avoid repetitive wrapper code, a custom annotation @ResponseResult is defined. An interceptor checks whether the current request’s handler method carries this annotation and sets a flag accordingly.
A global ResponseBodyAdvice implementation (combined with @ControllerAdvice ) then intercepts the response body; if the flag is set, it automatically wraps the original return value into a Result instance. The advice also handles exceptions by wrapping them into a failure Result .
Controller methods become much cleaner, for example:
@GetMapping("/order/{id}")
@ResponseResult
public Order getOrder(@PathVariable Long id) {
return orderService.findById(id);
}The article also discusses further refinements, such as using Hibernate Validator for input checks instead of manual null checks, caching annotation look‑ups to reduce reflection overhead, and returning raw business objects when appropriate.
Overall, the design provides a concise, elegant way to produce consistent API responses across a Spring backend, while remaining extensible for future enhancements.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.