1.背景
随着微服务的不断发展,api接口调用也是一个老大难问题,传统的api接口都是通过word,excel等文档记录,例如,有一个查询用户接口,前端开发,有pc端,微信端,移动端,而通过文档维护就不是很方便了开发测试。还得借助于postman等接口调试工具,而swagger就能很好的解决这些问题。
2.代码
2.1 pom.xml
<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>
2.2 config配置
package com.fqyd.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.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2 // 启用 Swagger
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 配置api扫描包的一个范围
.apis(RequestHandlerSelectors.basePackage("com.fqyd"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建文档信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 文档标题
.title("fqyd api文档")
// 版本号
.version("1.0")
// 描述
.description("风轻云淡的api文档")
.build();
}
}
2.3 控制类
package com.fqyd.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Description:
* Author: wude
* Date: 2019/11/19 9:43
* Modified By:
*/
@Api("swagger 控制类")
@RestController
public class SwaggerController {
@ApiOperation("swagger")
@ApiImplicitParam(name="name",value="用户名",dataType="String", paramType = "query")
@PostMapping("/hello")
public String hello(String name){
System.out.println("hello swagger"+name);
return "hello swagger "+name;
};
}
3 测试
http://localhost:82/swagger-ui.html
http://localhost:82 -------------是项目访问地址
swagger-ui.html -------------是swagger-ui的访问地址
个人感觉,还是蛮好用的,可以远离postman进行数据模拟测试。