SpringBoot 整合(五)Swagger2

269 阅读2分钟
原文链接: www.jianshu.com

日常我们开发完后端接口,如果是返回restful,写API文档是免不了的,Swagger可以帮我们解决大多数问题(自动生成API文档)。

他会帮我们生成一个html页面,大概就是这个样子。


好了,开始正文,如果你觉得有需要的话,往下看。

1. 添加依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

2. 修改启动项

添加注解

@EnableSwagger2   //开启swagger文档生成

3. 给Controller或者字段添加注释

3.1 给Controller方法添加注释。
    @ApiOperation(value = "条件查询用户")
    @GetMapping("/user")
    @JsonView(User.UserSimpleView.class)
    public List query(UserQueryCondition condition,
                      @PageableDefault(page = 2,size = 7,sort = "username,asc")Pageable pageable){

        System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.DEFAULT_STYLE));
        List<User> users = new ArrayList<>();
        users.add(new User());
        users.add(new User());
        users.add(new User());
        return users;
    }

然后访问http://127.0.0.1:8080/swagger-ui.html

3.2 给方法中的字段添加注释

方法一:

    @RequestMapping("/user/{id:\\d+}")
    @ApiImplicitParam(name = "id",value = "用户id")
    public User getInfo( @PathVariable String  id){
        User user = new User();
        user.setUsername("FantJ");
        return user;
    }

方法二:

    @RequestMapping("/user/{id:\\d+}")
    public User getInfo(@ApiParam("用户id") @PathVariable String  id){
        User user = new User();
        user.setUsername("FantJ");
        return user;
    }

方法一是再方法上面加注解,方法二是再参数位加注解。


3.3 给实体类的属性添加注释
    @ApiModelProperty("用户名")
    private String username;

最后所有注解的总结

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数