SpringBoot结合SpringDoc
SpringDoc介绍
SpringDoc基于swagger,并做了更多的对Spring系列各框架的兼容,用法上与Swagger3基本相同,并多了一些自己的配置,相较于Swagger3来说,更好用,支持也更好一点
开发环境
. JDK1.8
. SpringBoot 2.7.0
添加Maven依赖
<!--SpringDoc--> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.6</version> </dependency>
添加配置类
package cn.lixuelong.hs; import io.swagger.v3.oas.models.ExternalDocumentation; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI springShopOpenAPI() { return new OpenAPI() .info(new Info().title("SpringShop API") .description("Spring shop sample application") .version("v0.0.1") .license(new License().name("Apache 2.0").url("http://springdoc.org"))) .externalDocs(new ExternalDocumentation() .description("SpringShop Wiki Documentation") .url("https://springshop.wiki.github.org/docs")); } }
添加properties配置
#指定接口包扫描 springdoc.packagesToScan=cn.lixuelong.hs.api #或者指定访问接口路径扫描 #springdoc.pathsToMatch=/hs/**, /hsType/**
使用SpringDoc
- Controller上添加 @Tag 注解
- 接口方法上添加 @Operation 注解
- 对接口参数添加 @Parameters 和 @Parameter 注解
示例如下:
package cn.lixuelong.hs.api; import cn.lixuelong.hs.domain.Hs; import cn.lixuelong.hs.domain.HsType; import cn.lixuelong.hs.service.HsService; import cn.lixuelong.hs.service.HsTypeService; import com.alibaba.fastjson.JSONObject; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.Date; @Tag(name = "操作接口", description = "操作描述") @RestController @RequestMapping("hs") public class HsApi { @Resource private HsService hsService; @Resource private HsTypeService hsTypeService; @Operation(summary = "添加", description = "添加描述") @Parameters({ @Parameter(name = "name", description = "名字", required = true), @Parameter(name = "typeId", description = "类型ID", 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)); } @Operation(summary = "获取") @GetMapping("get") public JSONObject get(@Parameter(name = "id", description = "数据ID") Long id) { Hs hs = hsService.findById(id); return JSONObject.parseObject(JSONObject.toJSONString(hs)); } }