OpenAPI 3.0显示全部HTTP方法异常问题咨询
OpenAPI文档异常:接口显示全部HTTP方法的原因及解决办法
问题描述
编写了两个REST API接口,代码如下:
@RequestMapping("/inWithHibernate") @PutMapping public void inDbMobile() { hibernateInsert.inDB(); } @RequestMapping("/outWithHibernate") @GetMapping public MobileEntity outDbMobile(@RequestParam(name = "id")Long id) { return hibernateInsert.fromDB(id); }
预期OpenAPI文档仅展示PUT和GET方法,但实际显示了全部HTTP方法。使用的依赖配置:
<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.12</version> </dependency>
(OpenAPI 3.0截图:
)
原因分析
问题出在@RequestMapping与@PutMapping/@GetMapping的混用方式:
@RequestMapping未指定method属性时,默认匹配所有HTTP请求方法(GET、POST、PUT、DELETE等)。- 当同一个方法同时标注
@RequestMapping和特定HTTP方法注解时,SpringDoc的解析逻辑会优先识别@RequestMapping的默认规则,将该路径下的所有HTTP方法纳入文档生成范围,而非仅保留特定注解指定的方法。
解决办法
有两种简洁的修正方式:
直接使用带路径的HTTP方法注解(推荐):
移除@RequestMapping,将路径直接写入@PutMapping/@GetMapping中:@PutMapping("/inWithHibernate") public void inDbMobile() { hibernateInsert.inDB(); } @GetMapping("/outWithHibernate") public MobileEntity outDbMobile(@RequestParam(name = "id")Long id) { return hibernateInsert.fromDB(id); }在
@RequestMapping中明确指定请求方法:
保留@RequestMapping,补充method属性限定请求类型,与后续HTTP注解保持一致:@RequestMapping(value = "/inWithHibernate", method = RequestMethod.PUT) @PutMapping public void inDbMobile() { hibernateInsert.inDB(); } @RequestMapping(value = "/outWithHibernate", method = RequestMethod.GET) @GetMapping public MobileEntity outDbMobile(@RequestParam(name = "id")Long id) { return hibernateInsert.fromDB(id); }
验证
修改代码后重启服务,访问OpenAPI UI(默认路径/swagger-ui.html),即可看到文档仅展示对应的PUT和GET方法。
内容的提问来源于stack exchange,提问作者Jatel
相关产品推荐
相关产品推荐

