莫问前程 2020-06-14
什么是swagger?
Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。
swagger整合springboot的使用:
一、引入依赖
<!--添加Swagger依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!--添加Swagger-UI依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>二、编写配置类
package com.liusha.swagger.config;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration //标记为配置类
@EnableSwagger2 //开启Swagger在线接口文档
public class SwaggerConfig {
/**
* 添加摘要信息(Docket)
* .groupName("XXXX")配置这个Docket的组名
*/
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).groupName("组名:")
.apiInfo(new ApiInfoBuilder()
.title("标题:此处是配置UI界面显示的标题信息")
.description("描述:这里配置的是UI界面显示的对这个接口文档的描述信息")
//new Contact() 第一个参数是创建者,第二个是连接地址(可以不配),第三个参数是邮箱(可以不配)
.contact(new Contact("流-沙", "https://www.cnblogs.com/liusha-1/", ""))
.version("版本号:1.0")
.build())
.select()
//扫描Api接口的包监听是哪一个路径的
.apis(RequestHandlerSelectors.basePackage("com.liusha.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
}三、监听的controller类
package com.liusha.swagger.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ApiOperation()配置这个接口的描述信息
*/
@RestController
public class TestController {
@ApiOperation("测试SwaggerApi的接口")
@RequestMapping("/test")
public String test(){
return "hello swagger";
}
}四、运行之后点击http://localhost:8080/swagger-ui.html打开SwaggerUI界面如下:
