SpringBoot Swagger2 integrated online documentation

SpringBoot Swagger2 integrated online documentation

Foreword

I have to say, separating the front and rear ends of the development work has brought us many benefits, so that the front and rear end siege Lions have a lot smoother

Provide a good back-end to front-end interface documentation is a quality, it will also reduce the cost of communicating with each other

It is recommended that small partners an online, real-time updates interface documentation tool, Swagger2 , hands free is not a dream, with who knows who

Integrated SpringBoot

  1. Add dependent

    <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. Create a profileSwagger2Config.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. Start the project, access to documents Home http: // localhost: 8080 / swagger-ui.html, the effect is as follows

Login interface documentation examples

Code

  1. Interface type: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. Response categories: JSONResult.javaa unified response data interface format, small partners can adapt and use according to their needs

    @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;
            }
        }
    }

effect

Explanatory notes

@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;
}

to sum up

This article describes how to integrate Swagger2 instructions in SpringBoot, the quick start of usage, and the main annotations.

It is worth noting that the above mentioned JSONResult.java, it's generic affirmed that played a role in describing the details of attribute data in the interface document.

More than enough to let you easily control the content in the daily development Swagger2

Guess you like

Origin www.cnblogs.com/supergan/p/12080318.html