版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010050890/article/details/88963864
1、问题描述
随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、前后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。 前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要。没有API文档工具之前,大家都是手写API文档的(维护起来相当困难),在什么地方书写的都有,有在confluence
上写的,有在对应的项目目录下readme.md
上写的,每个公司都有每个公司的玩法,无所谓好坏。但是能称之为“框架”的,估计也只有swagger
了。
首先对swagger做一个简介吧:是一款让你更好的书写API文档的框架; swagger是后台开发的神器,也是前后端交流的渠道。你可以用swagger做什么?首先,你以后基本可以告别单元测试了;其次,你不用再写接口文档了,也不需要写完之后再去对文档进行维护了;swagger可以完全模拟http请求,入参出参和实际情况差别几乎为零。
2、操作步骤
2.1 配置:导入两个依赖包
implementation "io.springfox:springfox-swagger2:2.9.2"
implementation "io.springfox:springfox-swagger-ui:2.9.2"
2.2 springboot启用动类-添加swagger启用注解
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2 //添加swagger启用注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.3 添加swagger配置类
package com.example.demo.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.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.service.Contact;
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 注意修改此处的包名
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger2-集成系统")
.description("API接口文档")
.version("1.1.0")
.build();
}
}
2.4 在类、方法、参数上添加注解
package com.example.demo.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(value = "", description = "测试类")
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping("/get")
@ApiOperation(value = "测试Swagger", notes = "测试Swagger2", httpMethod = "GET", response = String.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "姓名", dataType = "String")
})
public String sayHello(String name) throws Exception {
return name + " hello Swagger!";
}
}
2.5 启动服务:浏览器输入http://ip:port/swagger-ui.html
http://localhost:8080/swagger-ui.html
出现下面的画面就代表大功告成