Swagger3介紹
開發中有很多接口的開發,接口需要配合完整的接口文檔才更方便溝通、使用,Swagger是一個用於自動生成在線接口文檔的框架,並可在線測試接口,可以很好的跟Spring結合,只需要添加少量的代碼和注解即可,而且在接口變動的同時,即可同步修改接口文檔,不用再手動維護接口文檔。Swagger3是17年推出的最新版本,相比於Swagger2配置更少,使用更方便
開發環境
. JDK 1.8
. SpringBoot 2.4.2
添加Maven依賴
<!--swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
添加Swagger配置類
package cn.lixuelong.hs;
import io.swagger.annotations.ApiOperation;
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.builders.ResponseBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
//swagger設置,基本信息,要解析的接口及路徑等
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
//設置通過什么方式定位需要自動生成文檔的接口,這里定位方法上的@ApiOperation注解
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//接口URI路徑設置,any是全路徑,也可以通過PathSelectors.regex()正則匹配
.paths(PathSelectors.any())
.build();
}
//生成接口信息,包括標題、聯系人,聯系方式等
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文檔")
.description("如有疑問,請聯系開發工程師")
.contact(new Contact("lixuelong", "https://www.cnblogs.com/lixuelong/", "lixuelong@aliyun.com"))
.version("1.0")
.build();
}
}
使用Swagger
- 在接口類上添加@Api(tags = "操作接口"),tags的值是該類的作用,在文檔頁面會顯示,value不會顯示
- 在需要生成文檔的接口上添加注解@ApiOperation
- 對請求參數添加@ApiParam
示例如下:
@Api(tags = "操作接口")
@RestController
@RequestMapping("hs")
public class HsApi {
@Resource
private HsService hsService;
@Resource
private HsTypeService hsTypeService;
@ApiOperation("添加")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "名字", dataType = "String", required = true),
@ApiImplicitParam(name = "typeId", value = "類型ID", dataType = "Long", required = true)
})
@PutMapping("add")
public JSONObject add(String name, Long typeId){
HsType hsType = hsTypeService.findById(typeId);
Hs hs = new Hs();
hs.setName(name);
hs.setType(hsType);
hs.setDateCreated(new Date());
hs = hsService.save(hs);
return JSONObject.parseObject(JSONObject.toJSONString(hs));
}
@ApiOperation("獲取")
@GetMapping("get")
public JSONObject get(@ApiParam(name = "id", value = "數據ID") Long id){
Hs hs = hsService.findById(id);
return JSONObject.parseObject(JSONObject.toJSONString(hs));
}
}
成果展示
啟動服務后,就可以查看在線文檔了,本地服務的地址是http://localhost:8080/swagger-ui/index.html,還可以通過Try it out 來測試