Spring Boot整合Swagger2的完整步骤详解

时间:2021-05-20

前言

swagger,中文“拽”的意思。它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,
而且还提供了在线文档的测试。另外swagger很容易构建restful风格的api。

一、Swagger概述

Swagger是一组围绕OpenAPI规范构建的开源工具,可帮助设计、构建、记录和使用REST API。

简单说下,它的出现就是为了方便进行测试后台的restful形式的接口,实现动态的更新,当我们在后台的接口

修改了后,swagger可以实现自动的更新,而不需要认为的维护这个接口进行测试。

二、Swagger常用注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponse:HTTP响应其中1个描述
  • @ApiResponses:HTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiParamImplicitL:一个请求参数
  • @ApiParamsImplicit 多个请求参数

三、SpringBoot整合Swagger

3.1 添加依赖

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

3.2 添加SwaggerConfiguration

通过@Configuration注解,表明它是一个配置类,@EnableSwagger2开启swagger2。

apiINfo()配置一些基本的信息。apis()指定扫描的包会生成文档。

再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会
展现在文档页面中)。select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来
展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容
(除了被@ApiIgnore指定的请求)。

package com.lance.learn.springbootswagger.configuration;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.service.Contact;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;/** * @author lance(ZYH) * @function Swagger启动配置类 * @date 2018-07-09 21:24 */@Configuration@EnableSwagger2public class SwaggerConfiguration { /** * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等 * @return */ @Bean public Docket createRestfulApi(){ return new Docket(DocumentationType.SWAGGER_2) .pathMapping("/") .select() .apis(RequestHandlerSelectors.basePackage("com.lance.learn.springbootswagger.controller")) //暴露接口地址的包路径 .paths(PathSelectors.any()) .build(); } /** * 构建 api文档的详细信息函数,注意这里的注解引用的是哪个 * @return */ private ApiInfo apiInfo(){ return new ApiInfoBuilder() //页面标题 .title("Spring Boot 测试使用 Swagger2 构建RESTful API") //创建人 .contact(new Contact("LanveToBigData", "http:///LanceToBigData/SpringBootLearning/tree/develop/SpringBoot-Swagger

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章