Spring Boot+springfox-swagger2中@ApiResponse的reference用法及响应示例展示
Alright, let's tackle your two questions about Swagger's @ApiResponse and springfox-swagger2 in Spring Boot— I’ve got hands-on experience with this setup, so I’ll walk you through it step by step.
reference Element in @ApiResponse for Response Samples The reference attribute in @ApiResponse is all about reusing pre-defined schemas (like your response DTOs) to avoid duplicating example data across your API docs. It links directly to a schema definition in the Swagger JSON spec, so Swagger UI can pull the sample values from that schema automatically.
How to use it:
- First, define your response model with
@ApiModeland@ApiModelProperty(to set field-level example values):@ApiModel(value = "UserResponse", description = "Success response for user details") public class UserResponse { @ApiModelProperty(value = "Unique user ID", example = "1001") private Long userId; @ApiModelProperty(value = "User's display name", example = "John Doe") private String fullName; // Getters and setters } @ApiModel(value = "ErrorResponse", description = "Error response for failed requests") public class ErrorResponse { @ApiModelProperty(value = "HTTP status code", example = "404") private Integer status; @ApiModelProperty(value = "Error message", example = "User not found") private String message; // Getters and setters } - Then, in your controller method’s
@ApiResponse, usereferenceto point to the schema’s path in the Swagger spec. The path follows the format#/definitions/YourModelName:@ApiResponse(code = 200, message = "Request successful", reference = "#/definitions/UserResponse") @ApiResponse(code = 404, message = "User not found", reference = "#/definitions/ErrorResponse")
Pro tip: If you use response = UserResponse.class instead of reference, springfox will automatically generate the reference for you. Use reference only if you need explicit control (e.g., pointing to a nested schema or a shared definition).
Here’s a complete setup to make sure each status code shows its own response sample in Swagger UI using Spring Boot + springfox-swagger2:
Step 1: Add Dependencies
First, include these in your pom.xml (adjust for Gradle if needed):
<!-- Springfox Swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!-- Swagger UI --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
Version 2.9.2 is stable and works well with most Spring Boot 2.x projects.
Step 2: Configure Swagger
Create a configuration class to enable Swagger and set up basic API info:
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() // Replace with your controller package .apis(RequestHandlerSelectors.basePackage("com.yourcompany.yourproject.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiMetadata()); } private ApiInfo apiMetadata() { return new ApiInfoBuilder() .title("User Management API") .description("API for managing user accounts") .version("1.0") .build(); } }
Step 3: Annotate Your Controller
Use @ApiResponses to group multiple @ApiResponse entries, each mapped to a status code and its corresponding response model:
@RestController @RequestMapping("/api/users") @Api(tags = "User Management") public class UserController { @GetMapping("/{userId}") @ApiOperation("Get user details by ID") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", reference = "#/definitions/UserResponse"), @ApiResponse(code = 400, message = "Invalid user ID", reference = "#/definitions/ErrorResponse"), @ApiResponse(code = 404, message = "User not found", reference = "#/definitions/ErrorResponse") }) public ResponseEntity<UserResponse> getUserById(@PathVariable Long userId) { // Your business logic here UserResponse response = new UserResponse(); response.setUserId(userId); response.setFullName("John Doe"); return ResponseEntity.ok(response); } }
Step 4: View the Result
Start your Spring Boot app and visit http://localhost:8080/swagger-ui.html (adjust port if needed). For your /api/users/{userId} endpoint, expand the "Responses" section— you’ll see each status code with its corresponding sample response pulled from your model’s @ApiModelProperty examples.
Bonus: Custom Raw JSON Examples
If you need a one-off example that doesn’t match your model, use the examples attribute instead of reference:
@ApiResponse(code = 200, message = "Success", examples = @Examples(value = { @Example( value = @ExampleProperty(mediaType = "application/json", value = "{\"userId\":1001,\"fullName\":\"John Doe\",\"email\":\"john@example.com\"}") ) }))
Wrap-up: Using reference keeps your API docs DRY and consistent, while combining it with @ApiModel and @ApiModelProperty ensures Swagger UI displays the correct sample for every status code.
内容的提问来源于stack exchange,提问作者Ramzsay

