swagger2 @ApiResponse的response不起作用

1,041 阅读2分钟

swagger可以生成比较友好的在线API说明文档。友好的API说明重要性不言而喻,因为所谓API,肯定就是被用来调用的,其中涉及到不同群体的工作,比如前端后端,本公司与第三方公司,等等。以往,制订数据接口,要正正经经地写一份正式的文档,名曰集成规范,大家对照着来。但现在有了swagger框架,就方便许多了,直接利用代码生成在线的接口说明文档。

swagger要产生比较实用的API说明文档,需要加一些标注。但是,这两天在实际应用过程中,却遇到一个问题,即无法生成响应数据的实体类说明。说明部分空空如也。

在这里插入图片描述
这样子的话,那么这个API说明文档意义就不大了。因为返回的数据中,有许多字段需要加上中文注释,否则根本不知道什么意思。

我们用的是swagger2。
pom.xml

<!-- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.5</version>
</dependency>

API所在控制器

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("api/work/production/total")
@Api(tags="产量产值")
public class WorkProductionChangeController {
    @Resource
    private WorkProductionChangeService workProductionChangeService;

    @PostMapping(path = "/all")
    @ApiOperation(value = "获取所有年份的总产量产值")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "返回所有年份的总产量产值",response = WorkProductionChange.class)
    })
    public JSONObject getAll() {
        return 。。。
    }
}

实体类WorkProductionChange

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
public class WorkProductionChange implements Serializable {
    private static final long serialVersionUID = -64757122210615988L;

    private Long id;

    private Integer year;
    @ApiModelProperty(value = "总产量(吨)")
    private Double totalWeight;
    @ApiModelProperty(value = "总产值(万元)")
    private Double totalMoney;

	。。。
}

按道理,response = WorkProductionChange.class,那么实体WorkProductionChange的信息应该出现在说明文档上,但从效果看,并没有。

狂搜索。后来终于看到有鬼佬说了这么一句:

Springfox 3.0 uses v3 models by default, but source.getResponses() gives wrong type. To workaround it for now, add:
springfox.documentation.swagger.use-model-v3=false in your application.properties.

英文烂,勉强看意思就是说,Springfox3.0默认用swagger v3来返回信息,但有个地方又出毛病了。为了避免愚蠢的系统犯错,你要在配置文件application.properties里加上一句:

application.properties

springfox.documentation.swagger.use-model-v3=false

如果是yml,就是

springfox:
  documentation:
    swagger:
      use-model-v3: false

太阳出来了。这才是我想要的。
在这里插入图片描述

参考文章:
github.com/springfox/s…