如何正确定义请求主体中的默认值?

发布于 2025-02-13 21:43:23 字数 1036 浏览 0 评论 0原文

我有一个端点,该端点接收一个带有可选字段的请求主体,我想指定一个默认值:

@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 nullgetResponse中并修改其值。 我还可以使用所需的默认值初始化该字段:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文