本文分享自天翼云开发者社区@《Springfox与SpringDoc——swagger如何选择(SpringDoc入门)》,作者: 才开始学技术的小白
(资料图片)
之前写过一篇关于swagger(实际上是springfox)的使用指南(https://www.ctyun.cn/developer/article/371704742199365),涵盖了本人在开发与学习的时候碰到的各种大坑。但由于springfox已经不更新了,很多项目都在往springdoc迁移
笔者也是花了一些时间试了一下这个号称“把springfox按在地下摩擦”的springdoc究竟好不好使,本文就来简单介绍下springdoc的使用以及优劣势
这里有个大坑一定要注意!!!
如果你跟我一样,现在使用的是springfox,但是想往springdoc迁移,结果试了一下发现还是springfox好用/懒得改那么多注解,还是想换回springfox,一定要把springdoc的maven依赖删掉!!!不然springboot会默认你用的是springdoc,导致swagger界面出不来
实际上springdoc的配置非常简单,使用的是OpenAPI类与GroupedOpenApi来配置
/**
* SpringDoc API文档相关配置
* Created by macro on 2023/02/02.
*/@Configurationpublic class SpringDocConfig {
@Bean
public OpenAPI mallTinyOpenAPI() {
return new OpenAPI()
.info(new Info().title("CTYUN API")
.description("SpringDoc API 演示")
.version("v1.0.0")
.license(new License().name("Apache 2.0").url("https://github.com/")))
.externalDocs(new ExternalDocumentation()
.description("SpringBoot项目")
.url("http://www.ctyun.com"));
}
@Bean
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.group("admin")
.pathsToMatch("/**")
.build();
}
//可以创建不同的GroupedOpenApi来判断不同的controller
@Bean
public GroupedOpenApi userApi() {
return GroupedOpenApi.builder()
.group("user")
.pathsToMatch("/user/**")
.build();
}}
默认配置之后直接进入:http://localhost:8080/swagger-ui/index.html 即可
注意这里与springfox略有不同(http://localhost:8080/swagger-ui.html)
这里转载一个写的非常全面的示例接口,原文可以去看:https://blog.csdn.net/zhenghongcs/article/details/123812583
/**
* 品牌管理Controller
* Created by macro on 2019/4/19.
*/@Tag(name = "PmsBrandController", description = "商品品牌管理")@Controller@RequestMapping("/brand")public class PmsBrandController {
@Autowired
private PmsBrandService brandService;
private static final Logger LOGGER = LoggerFactory.getLogger(PmsBrandController.class);
@Operation(summary = "获取所有品牌列表",description = "需要登录后访问")
@RequestMapping(value = "listAll", method = RequestMethod.GET)
@ResponseBody
public CommonResult> getBrandList() {
return CommonResult.success(brandService.listAllBrand());
}
@Operation(summary = "添加品牌")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasRole("ADMIN")")
public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) {
CommonResult commonResult;
int count = brandService.createBrand(pmsBrand);
if (count == 1) {
commonResult = CommonResult.success(pmsBrand);
LOGGER.debug("createBrand success:{}", pmsBrand);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("createBrand failed:{}", pmsBrand);
}
return commonResult;
}
@Operation(summary = "更新指定id品牌信息")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasRole("ADMIN")")
public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrandDto, BindingResult result) {
CommonResult commonResult;
int count = brandService.updateBrand(id, pmsBrandDto);
if (count == 1) {
commonResult = CommonResult.success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}", pmsBrandDto);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
}
return commonResult;
}
@Operation(summary = "删除指定id的品牌")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole("ADMIN")")
public CommonResult deleteBrand(@PathVariable("id") Long id) {
int count = brandService.deleteBrand(id);
if (count == 1) {
LOGGER.debug("deleteBrand success :id={}", id);
return CommonResult.success(null);
} else {
LOGGER.debug("deleteBrand failed :id={}", id);
return CommonResult.failed("操作失败");
}
}
@Operation(summary = "分页查询品牌列表")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole("ADMIN")")
public CommonResult
@Parameter(description = "页码") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "3")
@Parameter(description = "每页数量") Integer pageSize) {
List
return CommonResult.success(CommonPage.restPage(brandList));
}
@Operation(summary = "获取指定id的品牌详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasRole("ADMIN")")
public CommonResult
return CommonResult.success(brandService.getBrand(id));
}}
如果项目中使用了SpringSecurity,需要做两个配置来让springdoc正常使用:
1.在SpringSecurity配置类中放行白名单:"/v3/api-docs/**", "/swagger-ui/**"
2.在SpringDoc配置中增加对应内容,如下:
@Configurationpublic class SpringDocConfig {
private static final String SECURITY_SCHEME_NAME = "BearerAuth";
@Bean
public OpenAPI managerOpenAPI() {
return new OpenAPI()
.info(new Info().title("Galaxy-Cluster-Manager后端接口文档")
.description("提供给前端界面(portal)的接口文档")
.version("v1.0.0")
.license(new License().name("galaxy 1.2.0").url("https://gitlab.ctyun.cn/hpc/galaxy-parent/-/tree/v1.2.0")))
.externalDocs(new ExternalDocumentation()
.description("弹性高性能计算(CTHPC)")
.url("http://www.ctyun.cn"))
//以下是针对SpringSecurity的设置,同时还有设置白名单
.addSecurityItem(new SecurityRequirement().addList(SECURITY_SCHEME_NAME))
.components(new Components()
.addSecuritySchemes(SECURITY_SCHEME_NAME,
new SecurityScheme()
.name(SECURITY_SCHEME_NAME)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
@Bean
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("portal")
.pathsToMatch("/api/**")
.build();
}
}
实际上springfox也会有这个问题,使用对象作为query传参的时候,页面通常是这样的:
就没有办法逐个描述参数,也不能逐个调试(只能用json调试),非常的麻烦;springdoc有一个解决这个问题非常方便的注解:@ParameterObject
比如某一个控制器的入参是User user,我们只需要在这前面加上注解变为:@ParameterObject User user 即可,结果如下;
这里也有一个大坑:参数的类型可能会不正确,比如这里我们的id参数实际上是int,但显示出来是string,这个时候就需要我们在User类的属性中加上对应的注解,比如:
@Parameter(description = "id传参",example = "6")
再重启UI就会发现参数类型正确了
有的时候仅仅使用@Hidden并不能满足我们的需要,因为可能需要配置不同group的controller类,这个时候就需要在配置类中取设置扫包范围代码如下:
优势:SpringDoc有着非常好看的UI,以及比Springfox更加完善的参数注解体系,看起来非常舒服,并且还在不断更新与维护中
劣势:一些冷门功能还不完善,比如:
a.有十个接口,他们的url是一样的但是可以通过query参数来分别(如:@PostMapping(params = "action=QueryUsers"))这个时候springdoc只能通过扫包范围配置,来写多个GroupOpenApi来解决,非常的麻烦;springfox可以在docket创建的时候使用:docket.enableUrlTemplating(true); 这个方法即可解决
b.springdoc的网络配置可能会与springfox冲突,如果迁移,需要逐个尝试网络配置是否合适(主要是GsonHttpMessageConverter的配置)
c.兼容性问题仍需要观望,相对于springfox,springdoc的兼容性并没有那么好,在许多时候可能会出现序列化的乱码问题
总结:如果当前项目/工程已经集成了完备的springfox,建议不要轻易尝试迁移到springdoc,尤其是接口类型比较复杂、springfox配置docket比较多的项目;但如果是从头开始的项目,由于接口相对比较简单,可以采用springdoc,毕竟可以获得更加清晰明了的显示界面与参数解释。
X 关闭
X 关闭
本文分享自天翼云开发者社区@《Springfox与SpringDoc——swagger如何选择(SpringDoc入门)》,作者:才开始学技术的小白0 引言之前写过一篇关
2023青岛影视周4月6日开幕五大亮点带您抢鲜看4月6日至9日,2023青岛影视周在青岛西海岸新区举办。本届影视盛会主题为“新技术·新视界·新影都
今日,中科曙光与海南移动在海口签署合作协议,达成战略合作伙伴关系。双方将充分整合各自优势资源,围绕海南自贸港新基建、数字城市及重点行
这位媒体人表示,男足上了飞机之后,就和开派对一样,完全看不到敢输球的样子,媒体人表示从新西兰飞回国内的头等舱一共有六种酒,国足的球员
河南经济报记者杨磊通讯员赵泽轩面对“万人助万企”新方位、新常态、新要求,西峡农商银行躬身入局、主动作为,切实发挥金融在稳经济、保民生
4月6日,贵州证监局组织召开2023年辖区证券基金经营机构监管工作会,深入学习贯彻党的二十大精神和中央经济工作会议精神,学习传达2023年证监
dnf57礼盒送的东西,一般的礼物都会有级增加级别的领导的级别,所以你也可以选择送他一些有价值的礼物,如果你不想太多,可
半月谈|作者郑生竹朱国亮最近,一名来自内蒙古自治区、也不算肥胖的女大学生,被网红“引流”至南京河西美容医院,在医
4月6日上午,天空下着小雨,南雅中学52名学子来到了长沙市岳麓坪塘街道上善助残服务中心参加志愿服务及网络文明传播活动。“
招生办老师解答答初三是一个非常重要的阶段,对于即将面临高中选择的学生而言,选择一所合适的高中至关重要。在选择高中时,有一部分学生会选