SpringBoot整合Swagger

446 阅读3分钟

Swagger是一个用来描述后端接口的工具,可以通过配置和注解规则自动生成文档。

后端提供接口和数据,前端负责数据在页面的渲染,这是团队开发标准之一。我们学习一下如何使用SpringBoot整合Swagger。

地址:Chengyunlai/SpringBoot_Swagger: SpringBoot整合Swagger (github.com)

依赖

SpringBoot父工程我选择2.6.2

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

会报一个错误:Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

解决方法:

application.properties文件中,加入:

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

Swagger配置

这是一段通用的配置信息,请不要纠结。你只需要改这些地方:

  1. basePackage:写你的controller接口,包的地址
  2. title:写你项目的名称
  3. description:写项目的详细描述
  4. Contact:分别是:作者;作者网站(博客,github);邮箱
/**
 * @ClassName
 * @Description
 * @Author:chengyunlai
 * @Date
 * @Version 1.0
 **/
@EnableSwagger2
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                // 扫描接口的包
                .apis(RequestHandlerSelectors.basePackage("top.chengyunlai.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("详细信息")
                        .version("0.1")
                        .contact(new Contact("Chengyunlai","19550211498@163.com","19550211498@163.com"))
                        .license("Code And Love By Chengyunlai")
                        .licenseUrl("null")
                        .build());
    }
}

Controller

编写一个Controller接口,启动工程:

/**
 * @ClassName
 * @Description
 * @Author:chengyunlai
 * @Date
 * @Version 1.0
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @GetMapping("/all")
    public String getUserAll(){
        return "Success";
    }
}

访问:Swagger UI,看到如下效果表示整合成功。

image.png

注解描述

如果你对接口什么都不描述,这一点也不友好。Swagger其实给我们提供了一些注解帮助我们对接口有更好的描述。

@Api

作用在类上,对类进行描述。

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController

@ApiOperation

作用在方法上,对方法进行描述。notes是对方法的详细描述。

@ApiOperation(value = "查询所有用户",
notes = "描述:只有管理员才能查询询数据库中所有对应的用户")
@GetMapping("/all")
public String getUserAll(){
    return "Success";
}

@ApiImplicitParams

作用在方法上,对方法的参数进行描述。每个参数对应一个@ApiImplicitParam,包在{}中。

@ApiImplicitParam

对参数进行详细描述,name对应的是参数名,value是对参数的描述,dataType是提示该参数是什么类型,defaultValue是给别人通过Swagger调用该接口的默认参数,paramType表示该参数是一个路径参数(RESTful风格)。

@ApiOperation(value = "根据用户id查询用户")
@ApiImplicitParams({
        @ApiImplicitParam(name = "id",value = "用户id",dataType = "String",defaultValue = "1",paramType = "path")
})
@GetMapping("/{id}")
public String getUserById(@PathVariable String id){
    return "Success";
}

@ApiResponses

针对返回信息进行描述,定义多个可能返回的信息。对应通用返回类,俗称R

@ApiResponse

定义code,一般是Code枚举类中的信息,message是对应code的描述,例如权限不足等。

@ApiOperation(value = "根据用户id删除用户信息")
@ApiImplicitParams(
        @ApiImplicitParam(name = "id",value = "用户id",required = true,defaultValue = "1")
)
@ApiResponses({
        @ApiResponse(code = 2023,message = "错误咯"),
        @ApiResponse(code = 2024,message = "你错咯")
    })
@DeleteMapping("{/id}")
public String deleteById(@PathVariable String id){
    return "Success";
}

补充

实体类在Controller中被使用时,也会在在线文档中显示出来,但是有可能会遇到实体类描述是空的情况,解决方案:

  1. 有参构造
  2. get and set