本文最后更新于 2023-10-12,文章内容可能已经过时,请注意内容的辨别。

swagger2

简介

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

发展原因

在一些大型的项目当中,前后端也分离了,接口非常的多并且会伴随着改动,原来是前端和后端开会定接口,然后分别开发的,但是这样的话会产生时间或者说是扯皮的各种非开发的成本,所以swagger就出现了,通常意义上上他就是一个节约前后端沟通成本的一个工具

使用

1.导入依赖

 <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>

2.配置bean

package kj08.swaggerdemo.conf;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
​
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
​
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "kj08.swaggerdemo.controller";
​
public static final String VERSION = "1.0.0";
​
@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
            .paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
            .build();
}
​
private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("接口调用文档") //设置文档的标题
            .description("随便设置") // 设置文档的描述
            .version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
            .termsOfServiceUrl("http://www.baidu.com") //这里配置的是服务网站
            .build();
}
}
​
​

3.在controller上面加对应注解

package kj08.swaggerdemo.controller;
​
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
​
@Api(description = "学生模块接口")
@RestController
@RequestMapping("/stu")
public class StudentController {
​
​
​
​
​
@ApiOperation(value="登录", notes="登录", produces="application/json")
@RequestMapping(value="/login", method= RequestMethod.POST)
public String login(@RequestParam String user, @RequestParam String pwd) {
​
​
    return "SUCESS";
}
​
​
}
​
​

4.访问http://localhost:8080/swagger-ui.html

相关注解