首页 > 其他分享 >SpringBoot整合Swagger

SpringBoot整合Swagger

时间:2022-10-02 20:00:07浏览次数:75  
标签:springfox SpringBoot 接口 API 文档 整合 注解 Swagger

什么是Swagger?

Swagger是目前最常用的接口生成文档工具之一。

Swagger通过注解接口生成网页的在线文档,文档包括接口名、请求方法、参数、返回信息等。

更多信息参考:What is Swagger

为什么要使用Swagger

  • 可以生成一个具有互动性的API控制台,开发者可以用来快速掌握和测试API
  • 可以生成客户端SDK代码,用于各种不同平台上的实现
  • 可以在许多不同的平台上,从代码注释中自动生成文件
  • Swagger对SpringBoot有很好的支持

如何使用?

导入依赖

在pom.xml文件中导入Swagger相关依赖

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

配置文件

在config包下新建SwaggerConfig类。

该类主要用来配置文档名、组织名及对包生成在线API文档。

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi(){
        //设置组织名,对包生成API文档
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).enable(true)
                .select()
                //apis:添加swagger接口提取范围
                .apis(RequestHandlerSelectors.basePackage("controller所在包路径"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 设置整套文档标题
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxx项目API")
                .description("接口文档")
                .contact(new Contact("xxx项目名称", "网址", "邮箱"))
                .version("版本")
                .build();
    }
}

使用注解

注解概述

以下仅介绍常用注解:

  • @Api:修饰整个类,标记在Cotroller层的类上
  • @ApiOperation:描述一个接口,标记在Cotroller层的方法上
  • @ApiParam:单个参数描述
  • @ApiModel:使用JavaBean对象接收参数
  • @ApiModelProperty:当对象接收参数时,描述对象的字段
  • @ApiResponses:描述一组响应
  • @ApiResponse:HTTP响应其中的描述,用在@Responses中
  • @ApiIgnore:表示忽略这个API
  • @ApiError:当发生错误时的返回信息
  • @ApiImplicitParam:表示一个请求参数
  • @ApiImplicitParams:表示多个请求参数

代码实践

这里只使用最为常用的 @Api@ApiOperation

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

    @ApiOperation("根据条件查询用户")
    @PostMapping("/selectByConditions")
    public Result selectByConditions(@RequestBody UserPageTool userPageTool){
        System.out.println(userPageTool);
        return Result.success();
    }
}

访问在线文档

地址应为:http://项目的主机名:端口号/swagger-ui.html

我这里访问:http://localhost:8080/swagger-ui.html

效果展示

总结

  1. 引入依赖
  2. 配置config文件
  3. 在接口上使用相应注解
  4. 访问在线文档

标签:springfox,SpringBoot,接口,API,文档,整合,注解,Swagger
From: https://www.cnblogs.com/huang-guosheng/p/16749329.html

相关文章