我有几个项目运行 OAS 3.0 并使用 Gradle OpenAPI 生成器(更具体地说是 Gradle 插件)生成代码。我正在使用
JsonNullable
包裹类型,在大多数情况下,似乎一切都很好。但是我注意到以下行为似乎确实不错。考虑以下示例:
components:
schemas:
RequestDto:
type: object
properties:
id:
type: integer
nullable: false
name:
type: string
nullable: false
required:
- id
- name
如您所见,
name
属性既是non-nullable又是required,这又会导致生成以下代码:
public class RequestDto implements Serializable {
//Omitted noise
private String name;
public RequestDto name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
*/
@NotNull
@Schema(name = "name", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("name")
public String getName() {
return name;
}
}
在上述场景中,一切看起来都正常,因为该字段被标记为 Required 和 @NotNull 这是正确的。但是,当将该字段设置为
nullable: true
时,会生成以下内容。
public class RequestDto implements Serializable {
//Omitted noise
private String name;
/**
* Get name
* @return name
*/
@NotNull
@Schema(name = "name", requiredMode = Schema.RequiredMode.REQUIRED)
@JsonProperty("name")
public JsonNullable<String> getName() {
return name;
}
}
如您所见,该字段正确地包装在
JsonNullable
包装器中,并且也标记为 required
。但是 NotNull
注释仍然存在,这意味着我无法传递类似于以下内容的请求:
{
"id": 0,
"name": null
}
因为这在验证时实际上失败了。我可以通过从生成的代码中删除验证注释来轻松绕过此问题,但这不是一个可行的解决方案,因为我需要将其就位。
我的问题是:
nullable
和 required
字段将允许 null
值作为输入,无论这些值是否包含在 JsonNullable
中,反过来意味着没有 NotNull
注释。nullable
建模并同时对必填字段进行建模并使生成的代码正常工作?这确实是一个有点奇怪和复杂的实现,并且在 opeapi-generator 问题下也引起了很多关注。
然而,正如票证中所述,这种实现看起来是有意为之的。
情况 2:required=true & nullable=false 我们需要验证 字段存在,但开发人员应直接使用原始类型 -> 使用 JsonNullable 存储属性,在 getter/setter 上使用原始类型,在属性上使用 @Present 注释(而不是在 getter)和 getter 上的 @NotNull 用于验证
回答你的问题
但是 NotNull 注释仍然存在,这意味着我不能 传递类似于以下的请求:
{ "id": 0, "name": null }
不,您实际上可以通过上述请求。然后,实现将使用
@NotNull
只是为了确保从 getter 返回 JsonNullable
。
当您用
JsonNullable
打开 requestDto.getName().get()
时,您将获得包含的 null
值。
getter 中的
@NotNull
是为了确保始终返回非 null JsonNullable
。