如何正确定义请求主体中的默认值?
我有一个端点,该端点接收一个带有可选字段的请求主体,我想指定一个默认值:
@PostMapping(value = "/pass-obj", consumes = "application/json")
public MyResponse getResponse(@RequestBody MyRequest myRequest) { ... }
如果
public class MyRequest {
@Schema
String foo;
}
呼叫者未指定foo
,则其默认值应为“ ba”
。 对于@requestParameter
我知道您可以使用@requestParameter(defaultValue =“ ba”)
,所以我想,因为@schema
提供了一个属性我可以使用的同名名称:
public class MyRequest {
@Schema(defaultValue = "ba")
String foo;
}
但是,此默认值被完全忽略了。这是为什么?
我当然可以检查foo
null
在getResponse
中并修改其值。 我还可以使用所需的默认值初始化该字段:
public class MyRequest {
@Schema
String foo = "ba";
}
但是我不确定这是否是“正确的方式”,因为它不会与最终字段一起使用,并且我期望有一个注释。是否有更好的,推荐的方式来指定默认值?
I have an endpoint that receives a request body with optional fields that I want to specify a default value for:
@PostMapping(value = "/pass-obj", consumes = "application/json")
public MyResponse getResponse(@RequestBody MyRequest myRequest) { ... }
with
public class MyRequest {
@Schema
String foo;
}
If the caller doesn't specify foo
, its default value should be "ba"
.
For @RequestParameter
I know you can use @RequestParameter(defaultValue = "ba")
, so I figured, since @Schema
offers a property of the same name, that I could just use:
public class MyRequest {
@Schema(defaultValue = "ba")
String foo;
}
however, this default value gets completely ignored. Why is that?
I can of course check foo
for null
in getResponse
and modify its value.
I can also initialize the field with my desired default value:
public class MyRequest {
@Schema
String foo = "ba";
}
but I'm not sure if this is the "right way" as it would e.g. not work with final fields and I would have expected there to be an annotation for it. Is there a better, recommended way of specifying the default value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论