【发布时间】:2021-03-03 22:03:50
【问题描述】:
我使用这个库来生成文档:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.0</version>
</dependency>
我有这个控制器:
@RestController
public class TestController {
@GetMapping("/test{hz}")
public String test(@PathVariable(value = "hz", required = false) String hz) {
return "test";
}
}
但我得到了这份文件:
为什么required = false 不起作用?
我试过了:
@RestController
public class TestController {
@GetMapping("/test{hz}")
public String test(
@Parameter(description = "foo", required = false)
@PathVariable(value = "hz", required = false) String hz) {
return "test";
}
}
也不行
编辑:(@Helen 评论的答案)- 我当然知道:
@RestController
public class TestController {
@GetMapping(value = {"/test", "/test{hz}"})
public String test(
@Parameter(description = "foo", required = false)
@PathVariable(value = "hz", required = false) String hz) {
return "test";
}
}
我试过这个:
@PathVariable(value = "hz", required = false) Optional<String> hz
它使文档变得更糟。所以我没有添加这段代码。用{"/test", "/test{hz}"} 看起来是这样的:
【问题讨论】:
-
始终需要路径参数。要拥有可选的路径参数,您需要 define two paths - 带有和不带有该参数。
-
@Helen 我在我的问题中添加了更多信息。
-
@PathVariable必须有required = true,路径参数不能标记为可选。您需要定义 2 种单独的方法 - 一种带有hz参数,另一种没有。 -
@Helen 看起来很奇怪。你为什么这么断章取义? Spring注释
public @interface PathVariable有一个参数boolean required() default true;,我可以设置required == false,它在Spring中工作。 Swagger 注释public @interface Parameter有boolean required() default false;为什么我必须使用 2 个单独的方法? Spring 允许我使用一种方法@GetMapping(value = {"/test", "/test{hz}"})。你认为图书馆(swagger)必须规定规则吗? -
OpenAPI Specification 声明路径参数必须有
required: true。它们不能是可选的。可能 @PathVariable with required=false 是其他 API 描述格式的选项,但它与 OpenAPI 不兼容。您需要两个单独的方法,因为/test{hz}的方法必须有一个必需的路径参数,而/test的方法必须没有参数。
标签: spring swagger spring-restcontroller springdoc springdoc-openui