spring boot系列(二)集成Swagger文档

1,462 阅读2分钟

Swagger优势

  • 功丰富:支持多种注解,自动生成文档界面,支持在界面测试Api接口
  • 及时更新:在开发中写好注释,就可以自动更新文档
  • 使用简单:通过Pom.xml中添加依赖和简单配置,就可以内嵌于应用中发布Api接口文档界面,不需要独立部署服务

pom.xml依赖

<!--  集成 swagger 文档-->
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

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

添加swagger配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试接口文档")
                .description("RESTful风格的API文档")
                .version("1.0")
                .build();
    }

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

添加Controller

@Api("测试类")
@RestController()
@RequestMapping("test")
public class TestController {

    @ApiOperation("输出hello信息(不带参数)")
    @GetMapping("/hello")
    @ResponseBody
    public String printHello() {
        return "my first spring boot project";
    }


    @ApiOperation("输出hello信息(携带参数)")
    @GetMapping("/hello_1")
    @ResponseBody
    public String printHello(@ApiParam(value = "用户名称",required = true) @RequestParam String name) {
        return String.format("%s:hello",name);
    }

}

说明:

  • ==@Api(value="")==:用于类说明
  • == @ApiOperation(value="")==:用于方法说明
  • ==@ApiParm(value="",required=true)==:用于参数说明,其中 ==required== 表示该参数是否必需(即是否可为空,默认为false,表示该参数可以为空)
  • ==@RequestParm== 和 ==@ApiParm== 等效

启动服务,浏览器输入localhost:8090/swagger-ui.html


测试Api接口

先测试不带参数的接口,点击 try it out,然后点击execute,

接口测试通过

再来测试都带有携带参数的接口

接口测试通过


添加请求参数

在有些场景下,需要在接口中携带一些通用参数,例如采取token验证逻辑的接口,一般会将token一起传入后台。接下来对SwaggerConfig进行修改,添加默认参数

修改SwaggerConfig类,主要是修改createRestApi方法

    @Bean
    public Docket createRestApi() {
        ParameterBuilder parameterBuilder = new ParameterBuilder();
        List<Parameter> parameterBuilders = new ArrayList<>();
        parameterBuilder.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false);
        parameterBuilders.add(parameterBuilder.build());

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().
                apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build()
                .globalOperationParameters(parameterBuilders);

    }

可以看到两个接口都增加了一个token参数,但是接口中并没有定义这个参数