You need to enable JavaScript to run this app. 如何为不同HTTP状态码配置@ApiModelProperty的差异化Swagger响应示例
优惠活动
大模型
产品
解决方案
定价
更多

如何为不同HTTP状态码配置@ApiModelProperty的差异化Swagger响应示例

Springfox通用错误响应实体的差异化示例配置方案

问题背景

项目内存在全接口通用的错误响应实体ErrorDetails,代码结构如下:

public class ErrorDetails {
  private Date timestamp;
  private String message;
  private String details;
  private int code;

  public ErrorDetails(Date timestamp, String message, String details, int code) {
    this.timestamp = timestamp;
    this.message = message;
    this.details = details;
    this.code = code;
  }
}

当前依赖Swagger的@ApiModel、@ApiModelProperty注解配置接口文档的示例值,需要满足以下核心诉求:

  • 不同HTTP状态码匹配完全独立的错误示例:例如400状态码的示例消息为Page not found,500状态码的示例和前者完全独立
  • 同一HTTP状态码下,不同业务场景的示例要做区分:例如同是404状态码,需要分别展示「Employee not found」「Store not found」这类不同业务含义的错误示例

但现有配置方式只能给实体类字段设置全局单一的示例值,无法适配上述差异化需求。

已尝试的失效方案

  • 在全局Docket配置中设置通用错误响应
    该方式只能配置跨接口通用的固定错误示例,无法满足同一状态码下、不同接口/不同业务场景的示例差异化要求。
  • 结合@ApiResponse搭配@Example注解配置示例
    配置后不生效,Springfox官方也明确说明该写法不适配当前版本,建议回归@ApiModelProperty的配置逻辑。此前使用的无效配置示例如下:
    @ApiResponse(code = 500, message = "Internal server error", response = ErrorDetails.class, examples = @Example(value = @ExampleProperty(value = "{\"timestamp\": \"1598947603319\", \"message\":\"Operation failed\", \"details\":\"Operation failed due to Runtime exception\", \"code\": \"500\"}", mediaType = "application/json")))
    
    配置后Swagger文档展示的示例和预期完全不符。

可落地的解决方法

核心逻辑

Springfox原生不支持同一个实体类在不同响应场景下复用时设置差异化字段示例,可通过自定义模型增强插件,针对不同的响应场景,动态给Swagger内存中的模型属性注入对应示例值,既保留通用实体的复用性,又无需为每个场景编写重复的实体子类。

步骤1:实现Swagger自定义模型增强插件

实现ModelPropertyBuilderPlugin、SwaggerPlugin两个接口,重写属性构建逻辑,通过请求的接口路径、状态码、业务标签匹配对应的示例配置:

@Component
public class CustomErrorModelExamplePlugin implements ModelPropertyBuilderPlugin, SwaggerPlugin {
    private final TypeResolver typeResolver;
    // 预置所有场景的示例映射,key为「接口标识-状态码-字段名」,value为对应字段的示例值
    private final Map<String, Object> exampleMapping = new HashMap<>();

    public CustomErrorModelExamplePlugin(TypeResolver typeResolver) {
        this.typeResolver = typeResolver;
        // 配置404-员工不存在的场景示例
        exampleMapping.put("GET /api/employee/{id}-404-message", "Employee not found");
        exampleMapping.put("GET /api/employee/{id}-404-details", "No employee exists with the requested ID");
        exampleMapping.put("GET /api/employee/{id}-404-code", 404);
        // 配置404-门店不存在的场景示例
        exampleMapping.put("GET /api/store/{id}-404-message", "Store not found");
        exampleMapping.put("GET /api/store/{id}-404-details", "No store exists with the requested ID");
        exampleMapping.put("GET /api/store/{id}-404-code", 404);
        // 配置全局通用的500系统异常场景示例
        exampleMapping.put("*-500-message", "Operation failed");
        exampleMapping.put("*-500-details", "Runtime exception occurred during request processing");
        exampleMapping.put("*-500-code", 500);
    }

    @Override
    public void apply(ModelPropertyContext context) {
        // 仅处理ErrorDetails类型的属性,跳过其他实体的构建逻辑
        Class<?> rawType = context.getBeanPropertyDefinition().get().getRawPrimaryType();
        if (rawType != ErrorDetails.class) {
            return;
        }
        // 获取当前构建的接口上下文,匹配对应的示例规则
        OperationContext operationContext = context.getOperationContext().orElse(null);
        if (operationContext == null) {
            return;
        }
        String currentFieldName = context.getBeanPropertyDefinition().get().getName();
        int responseCode = operationContext.getOperation().getResponseCode();
        String requestPath = operationContext.requestMappingPattern();
        // 拼接key匹配预置的示例值,支持通配符匹配全局规则
        String matchKey = String.format("%s-%s-%s", requestPath, responseCode, currentFieldName);
        Object exampleValue = exampleMapping.getOrDefault(matchKey, 
            exampleMapping.get(String.format("*-%s-%s", responseCode, currentFieldName))
        );
        // 匹配到对应示例就覆盖默认值
        if (exampleValue != null) {
            context.getBuilder().example(exampleValue);
        }
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return DocumentationType.SWAGGER_12.equals(delimiter) 
            || DocumentationType.SWAGGER_2.equals(delimiter);
    }
}

步骤2:清理原有全局固定示例配置

将ErrorDetails类上@ApiModelProperty中写死的example属性全部移除,所有示例值由上述自定义插件按场景动态注入。

步骤3:优化接口上的@ApiResponse配置

删除不生效的@Example配置,仅标注对应的响应类型、状态码、场景标识即可,Swagger会自动调用自定义插件匹配对应的示例:

// 员工详情接口的404场景配置
@ApiResponse(code = 404, message = "Employee not found", response = ErrorDetails.class)
// 门店详情接口的404场景配置
@ApiResponse(code = 404, message = "Store not found", response = ErrorDetails.class)
// 全局通用的500场景配置
@ApiResponse(code = 500, message = "Internal server error", response = ErrorDetails.class)

最终效果

配置完成后,Swagger文档会根据每个接口对应的状态码,自动匹配注入差异化的示例内容:

  • 员工详情接口的404响应,会展示「Employee not found」对应的完整错误示例
  • 门店详情接口的404响应,会展示「Store not found」对应的完整错误示例
  • 所有接口的500响应,会统一展示系统级错误的示例内容
    全程不会产生大量冗余的实体类代码,也不会出现示例配置不生效的问题。

内容的提问来源于stack exchange,提问作者Rahul Raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.28 02:15:03