You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Springfox 2.9.2中@ApiResponse如何配置返回List<MyErrorObject>错误响应

问题背景

使用的Swagger依赖为springfox 2.9.2版本,依赖配置如下:

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
  <scope>compile</scope>
</dependency>
响应结构说明

接口传入非法参数时,会返回MyErrorObject对象组成的列表,MyErrorObject结构如下:

MyErrorObject 
{
  Date date;
  String errorCode;
  String errorMessage;
  //getters //setters
}

实际返回示例:

[
    {
        "date": "2021-09-22",
        "errorCode": "6548",
        "errorMessage": "there are no booking available in selected city"
    },
    {
        "date": "2021-09-22",
        "errorCode": "2649",
        "errorMessage": "your age does not allow you to travel to this location"
    }
]
问题现象

尝试通过如下写法配置@ApiResponse注解时出现编译错误:

@ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST,
          message = ErrorConstants.NotAllowed, response=List<MyErrorObject>.class)

报错信息:Syntax error, insert "}" to complete MemberValueArrayInitializer

解决方法

Java语法本身不支持直接获取带泛型的类字面量,你可以使用@ApiResponse提供的responseContainer属性声明容器类型:

  • response参数填写列表元素的类对象MyErrorObject.class
  • responseContainer参数填写固定值"List",标识返回结果是对应元素的List集合

正确配置如下:

@ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST,
          message = ErrorConstants.NotAllowed, 
          response = MyErrorObject.class,
          responseContainer = "List")

配置完成后Swagger会自动生成符合预期的数组格式响应示例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:39:03