Spring Boot中使用Swagger

1. 启用Swagger
1.1 启用注解扫描和文档接口

直接在POM文件引入依赖

<dependency>
    <groupId>io.springfoxgroupId>
    <artifactId>springfox-swagger2artifactId>
    <version>2.9.2version>
dependency>
1.2 启动swagger-ui

目前看到的选项有2个:

  • swaager-ui ,访问地址: http://127.0.0.1:18080/swagger-ui.html
    <dependency>
        <groupId>io.springfoxgroupId>
        <artifactId>springfox-swagger-uiartifactId>
        <version>2.9.2version>
    dependency>
  • swagger-bootstrap-ui ,也叫knife4j ,访问地址: http://127.0.0.1:18080/doc.html
    <dependency>
      <groupId>com.github.xiaoymingroupId>
      <artifactId>swagger-bootstrap-uiartifactId>
      <version>${lastVersion}version>
    dependency>

我更喜欢swagger-bootstrap-ui的风格

1.3 创建Swagger配置类
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {

        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
    //                .apis(RequestHandlerSelectors.any())
                    .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                    .paths(PathSelectors.any())
                    .build();
        }

        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("标题lws") //标题
                    .description("简介lws") //简介
                    .termsOfServiceUrl("服务条款lws") //服务条款
                    .contact(new Contact("randy", "", "[email protected]"))
                    .version("1.0.lws") //版本
                    .build();
        }
    }

Spring Boot中使用Swagger_第1张图片

2. 注解
2.1 @Api

@Api注解在Controller上,通过tags指定指定名称(左侧菜单的名称),tags可以指定多个值,多种使用场景通过指定相同的tag值将所有的API分组在一起。

@Api还有valuedescription属性,description已经@Deprecatedvalue号称会被当成tags值,实际测试下来无效

    @RestController
    @RequestMapping("/v1")
    @Api(tags = {"测试Swagger的注解使用"})
    public class HelloworldController {
    }

Spring Boot中使用Swagger_第2张图片

2.2 @ApiOperation

@ApiOperation用于注解到Controller上的方法,对应一个对外提供的接口。目前有4个属性:

属性 描述
value 对操作的简单说明
notes 对操作的详细说明
httpMethod HTTP请求类型,可选:GET HEAD POST PUT DELETE OPTIONS PATCH
code HTTP状态码,默认为200
produces 输出的Content-Type
consumes 输入的Content-Type

示例

    @RequestMapping("say")
    @ApiOperation(value = "用于打印用户输入信息", notes = "这是个什么鬼啊啊啊", httpMethod = "GET")
    public String say(@RequestParam("message") String message) {
        return message;
    }

Spring Boot中使用Swagger_第3张图片

2.3 @ApiParam
属性 描述
name 参数名称,因此这个一般应该是字母
value 参数说明
defaultValue 参数默认值
required 参数是否必须

参数类型会通过反射获取,如果参数是基本类型会显示在数据类型字段,如果参数是自定义的类,会同时显示在数据类型schema字段

2.3.1 示例: query param

基本上只有value字段对接收说明有意义, example字段是在页面上调试给的示例值

@RequestMapping("say")
@ApiOperation(value = "用于打印用户输入信息", notes = "这是个什么鬼啊啊啊", httpMethod = "GET")
public String say(@ApiParam(value = "参数描述", example = "10086") @RequestParam("message") Integer message) {
    return "";
}

Spring Boot中使用Swagger_第4张图片

2.3.2 示例: 使用请求体,并用一个对象接收参数

使用@RequestBody的场景下,指定@ApiParam唯一有用的属性的value,指定其他参数没有效果

    @PostMapping("say2")
    @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
    public String say2(@ApiParam(value = "参数描述") @RequestBody ApFissionLog apFissionLog) {
        return "";
    }

Spring Boot中使用Swagger_第5张图片

2.4 @ApiImplicitParams 和 @ApiImplicitParam

@ApiParam相同作用,但是不把注解混合到代码内部,可读性更强,个人更喜欢这种方式

    @PostMapping("say3")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cavatar",value = "value1",example = "10001", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "cnickname",value = "value2",example = "example2", dataType = "string", paramType = "query")
    })
    public String say3(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
        return "";
    }

Spring Boot中使用Swagger_第6张图片

2.5 @ApiResponse

定义接口的返回值,示例中say4say5方法的表现基本一致,没发现注解的特殊意义

属性 描述
code HTTP状态码
message 状态码的文本描述
response 返回值的class
responseContainer 返回容器类型时使用,有效值: List Set Map
    @PostMapping("say4")
    public ApFissionLog say4(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
        return new ApFissionLog();
    }

    @PostMapping("say5")
    @ApiResponse(code = 200,message = "返回描述", response = ApFissionLog.class)
    public ApFissionLog say5(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
        return new ApFissionLog();
    }
2.6 @ApiModel和@ApiModelProperty

当请求和响应是POJO的时候特别有用,现实场景中这又是最常用的情况。

@ApiModel用于指定POJO类的描述,提供更可读的类型名称(这个个人觉得没用,直接展示现有类名挺好)。

属性 描述
value model的别名,默认为类名
description model的详细描述

@ApiModelProperty用于描述POJO里的字段

属性 描述
value 属性简短描述
example 属性的示例值
required 是否为必须值
    @PostMapping("say6")
    @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
    public ApFissionLog say6(@RequestBody ApFissionLog apFissionLog) {
        return new ApFissionLog();
    }

通过在ApFissionLog类上添加注解


@ApiModel(value = "model类名字", description = "描述信息")
public class ApFissionLog {

    @ApiModelProperty(value = "C用户的昵称", notes = "notes", example = "AAA-BBB-CCC", required = true)
    private String cnickname;
    @ApiModelProperty(value = "C用户的头像", notes = "notes", example = "http://www.aaa.com/avtar.png", required = true)
    private String cavatar;

}

Spring Boot中使用Swagger_第7张图片

3. API分组

通过在Swagger的配置类里创建两个Docket对象,扫描不同的包就能完成分组

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean("defaultApi")
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组1")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean("groupApi")
    public Docket createGroupApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组2")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题lws") //标题
                .description("简介lws") //简介
                .termsOfServiceUrl("服务条款lws") //服务条款
                .contact(new Contact("randy", "", "[email protected]"))
                .version("1.0.lws") //版本
                .build();
    }
}

Spring Boot中使用Swagger_第8张图片

4. 完整示例
4.1 pom.xml 添加依赖
    <dependency>
        <groupId>io.springfoxgroupId>
        <artifactId>springfox-swagger2artifactId>
        <version>2.9.2version>
    dependency>

    <dependency>
        <groupId>com.github.xiaoymingroupId>
        <artifactId>swagger-bootstrap-uiartifactId>
        <version>1.9.6version>
    dependency>
4.2 Swagger Config 类
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean("defaultApi")
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组1")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }

    @Bean("groupApi")
    public Docket createGroupApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("分组2")
                .select()
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.dwpro"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("标题lws") //标题
                .description("简介lws") //简介
                .termsOfServiceUrl("服务条款lws") //服务条款
                .contact(new Contact("randy", "", "[email protected]"))
                .version("1.0.lws") //版本
                .build();
    }
}

4.3 Controller类
    @RestController
    @RequestMapping("/v1")
    @Api(tags = {"测试Swagger的注解使用"})
    public class HelloworldController {


        @RequestMapping("say1")
        @ApiOperation(value = "用于打印用户输入信息", notes = "这是个什么鬼啊啊啊", httpMethod = "GET")
        public String say1(@ApiParam(value = "参数描述", example = "10086") @RequestParam("message") Integer message) {
            return "";
        }

        @PostMapping("say2")
        @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
        public String say2(@ApiParam(value = "参数描述") @RequestBody ApFissionLog apFissionLog) {
            return "";
        }

        @PostMapping("say3")
        @ApiImplicitParams({
                @ApiImplicitParam(name = "cavatar",value = "value1",example = "10001", dataType = "int", paramType = "query"),
                @ApiImplicitParam(name = "cnickname",value = "value2",example = "example2", dataType = "string", paramType = "query")
        })
        public String say3(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
            return "";
        }

        @PostMapping("say4")
        public ApFissionLog say4(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
            return new ApFissionLog();
        }

        @PostMapping("say5")
        @ApiResponse(code = 200,message = "返回描述", response = ApFissionLog.class)
        public ApFissionLog say5(@RequestParam("cavatar") String cavatar, @RequestParam("cnickname") String cnickname) {
            return new ApFissionLog();
        }

        @PostMapping("say6")
        @ApiOperation(value = "测试请求体", notes = "这是个什么鬼啊啊啊", httpMethod = "POST")
        public ApFissionLog say6(@RequestBody ApFissionLog apFissionLog) {
            return new ApFissionLog();
        }


    }
4.4 POJO类
    @Data
    @ApiModel(value = "model类名字", description = "描述信息")
    public class ApFissionLog {

        @ApiModelProperty(value = "C用户的昵称", notes = "notes", example = "AAA-BBB-CCC", required = true)
        private String cnickname;
        @ApiModelProperty(value = "C用户的头像", notes = "notes", example = "http://www.aaa.com/avtar.png", required = true)
        private String cavatar;

    }

你可能感兴趣的:(spring,boot,后端,java)