如何通过Springfox为Spring Boot REST API全局配置x-request-id响应头
x-request-id Response Header (with Swagger Global Display) Great question! Manually adding @ApiResponses to every endpoint is definitely tedious. Let's fix this with two core solutions: first, globally attaching the x-request-id header to all API responses, and second, configuring Swagger to automatically show this header for all endpoints without per-annotation work.
1. Globally Add x-request-id to All API Responses
You have two reliable approaches here—pick the one that fits your use case best:
Option 1: Use a Servlet Filter (Recommended for Full Coverage)
A Filter works for all responses, including error/exception responses, which makes it the most comprehensive choice. Create a Filter component like this:
import jakarta.servlet.*; import jakarta.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.UUID; @Component public class RequestIdFilter implements Filter { private static final String REQUEST_ID_HEADER = "x-request-id"; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; // Generate a unique UUID for the request ID String requestId = UUID.randomUUID().toString(); // Attach the header to the response httpResponse.setHeader(REQUEST_ID_HEADER, requestId); // Continue processing the request chain.doFilter(request, response); } }
Once you add this component, every request (success or error) will include the x-request-id header in its response.
Option 2: Use ResponseBodyAdvice (For Controller-Only Responses)
If you only need to handle responses from your Controller methods (and will handle exceptions separately with @ControllerAdvice), use ResponseBodyAdvice:
import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; import java.util.UUID; @ControllerAdvice public class RequestIdResponseBodyAdvice implements ResponseBodyAdvice<Object> { private static final String REQUEST_ID_HEADER = "x-request-id"; @Override public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) { return true; // Apply to all Controller methods } @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { // Add the request ID header before sending the response body response.getHeaders().add(REQUEST_ID_HEADER, UUID.randomUUID().toString()); return body; } }
2. Configure Swagger to Show x-request-id Globally
No more per-endpoint @ApiResponses! We'll configure Swagger to automatically include this header for all endpoints. The approach varies slightly based on whether you're using SpringDoc OpenAPI (modern, recommended) or SpringFox Swagger 2 (older):
For SpringDoc OpenAPI (Swagger 3)
Create an OpenAPI configuration bean that uses OpenApiCustomizer to attach the header to all operations and responses:
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.headers.Header; import io.swagger.v3.oas.models.media.StringSchema; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI customOpenAPI() { // Define the x-request-id header schema Header requestIdHeader = new Header() .description("Auto generated unique request ID") .schema(new StringSchema()); return new OpenAPI() // Register the header as a reusable component .components(new io.swagger.v3.oas.models.Components() .addHeaders("x-request-id", requestIdHeader)) // Attach the header to every response of every operation .customizer(openApi -> { openApi.getPaths().values().forEach(pathItem -> { pathItem.readOperations().forEach(operation -> { operation.getResponses().values().forEach(response -> { response.addHeaderObject("x-request-id", requestIdHeader); }); }); }); }); } }
After this, every endpoint in your Swagger UI will display the x-request-id header under its responses.
For SpringFox Swagger 2
If you're still using SpringFox, configure the Docket to add global response headers for all HTTP methods:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.bind.annotation.RequestMethod; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ResponseHeader; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.builders.ResponseBuilder; import java.util.Arrays; import java.util.Collections; @Configuration public class SwaggerConfig { @Bean public Docket api() { // Define the x-request-id response header ResponseHeader requestIdHeader = new ResponseHeader( "x-request-id", "Auto generated unique request ID", Collections.emptyList() ); Docket docket = new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.package")) // Replace with your package .paths(PathSelectors.any()) .build(); // Attach the header to all HTTP methods and their 200 responses Arrays.asList(RequestMethod.values()).forEach(method -> { docket.globalResponseMessage(method, Collections.singletonList( new ResponseBuilder() .code("200") .responseHeaders(Collections.singletonList(requestIdHeader)) .build() )); }); return docket; } }
This will ensure the x-request-id header shows up in Swagger for every endpoint's 200 response (you can add more response codes if needed).
Final Notes
- The Filter approach is preferred because it covers error responses (like 404, 500) that
ResponseBodyAdvicemight miss. - The Swagger configurations above eliminate the need for any per-endpoint
@ApiResponsesannotations for this header.
内容的提问来源于stack exchange,提问作者Soumen Dass

