SpringBoot集成Swagger2在线文档

SpringBoot集成Swagger2在线文档

前言

不得不说,前后端分离开发的工作方式给我们带来诸多好处, 让前后端攻城狮们顺畅了不少

后端给前端提供良好的接口文档是一种品质,也会减少彼此的沟通成本

这里推荐小伙伴们一款在线、实时更新接口文档工具,Swagger2,解放双手不是梦,谁用谁知道

集成SpringBoot

  1. 添加依赖

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.0</version>
    </dependency>
  2. 创建配置文件Swagger2Config.java

    @Configuration
    @EnableSwagger2
    public class Swagger2Config {
    
         // 项目启动后,查看文档:http://{上下方路径}/swagger-ui.html
        // 如,http://localhost:8080/swagger-ui.html
    
        // Swagger2 核心配置 docket
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)  // 指定api类型
                    .apiInfo(createApiInfo())               //定义文档汇总信息
                    .select().apis(RequestHandlerSelectors
                            .basePackage("cn.supergan.controller")) //指定controller包
                    .paths(PathSelectors.any()) //所有controller
                    .build();
        }
    
         // 构建文档信息
        public ApiInfo createApiInfo() {
            return new ApiInfoBuilder()
                    .title("XXX 接口API")   //文档页标题
                    .contact(new Contact("小动物不困", "https://www.supergan.cn", "[email protected]"))   //联系人信息
                    .description("XXX 接口API,实时更新,如有问题,及时沟通") //详细信息
                    .version("1.0")   //文档版本号
                    .termsOfServiceUrl("https://www.supergan.cn")    //网站地址
                    .build();
        }
    }
  3. 启动项目,访问文档首页http://localhost:8080/swagger-ui.html,效果如下

登录接口文档示例

代码

  1. 接口类:PassportController.java

    @Api(tags = "登录")
    @RestController
    public class PassportController {

    @ApiOperation(value = "登录", notes = "使用用户名和密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户名", name = "username", required = true),
            @ApiImplicitParam(value = "密码", name = "password", required = true)
    })
    @PostMapping("/login")
    public JSONResult<Users> login(@RequestParam String username, @RequestParam String password) {
        Users users = new Users();
        // TODO 此处省略登录相关业务逻辑
        users.setUsername(username);
        users.setPassword(password);
        return JSONResult.ok(users);
    }
  2. 用户类:Users.java

    @ApiModel(description = "用户")
    @Data
    public class Users {
        @ApiModelProperty("用户名")
        private String username;
        @ApiModelProperty("密码")
        private String password;
    }
  3. 响应类:JSONResult.java,统一接口的数据响应格式,小伙伴们可根据自己的需求改造和使用

    @Data
    public class JSONResult<T> {
        private Integer status;
        private String message;
        private T data;
    
        public JSONResult(ResultCode code) {
            this.setMessage(code.getMessage());
            this.setStatus(code.getStatus());
        }
    
        public static <T> JSONResult<T> ok(T data) {
            JSONResult<T> jsonResult = new JSONResult<T>(ResultCode.SUCCESS);
            jsonResult.setData(data);
            return jsonResult;
        }
    
        @Getter
        enum ResultCode {
            SUCCESS(200, "OK"),
            UN_KNOW_ERROR(500, "未知异常")
            ;
            private Integer status;
            private String message;
    
            ResultCode(Integer status, String message) {
                this.status = status;
                this.message = message;
            }
        }
    }

效果

注解说明

@Api

@Api:用在请求的类上,说明该类的作用
    tags="说明该类的作用"
    value="该参数没什么意义,所以不需要配置"
  
示例
@Api(tags="APP用户注册Controller")

@ApiOperation

@ApiOperation:用在请求的方法上,说明方法的作用
    value="说明方法的作用"
    notes="方法的备注说明"
  
示例
@ApiOperation(value = "登录", notes = "使用用户名和密码登录")

@ApiImplicitParams

@ApiImplicitParams:用在请求的方法上,包含一组参数说明
    @ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一个请求参数的配置信息       
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

示例
@ApiImplicitParams({
        @ApiImplicitParam(value = "用户名", name = "username", required = true),
        @ApiImplicitParam(value = "密码", name = "password", required = true)
})

@ApiResponses

@ApiResponses:用于请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

示例
@ApiResponses({
    @ApiResponse(code=400,message="请求参数错误"),
    @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})

@ApiModel

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性
  
示例
@ApiModel(description = "用户")
@Data
public class Users {
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
}

总结

本文介绍了在SpringBoot中如何集成Swagger2,快速上手的用法,和主要注解的说明。

其中值得注意的是,上文中提到的JSONResult.java,它的泛型申明,在接口文档中起到了描述data属性详情的作用。

以上内容足以让你在日常开发中轻松驾驭Swagger2

猜你喜欢

转载自www.cnblogs.com/supergan/p/12080318.html