在生成的OpenAPI文档中,springdoc-openapi库自动将某些属性标记为required。例如,注释为@NotNull
的属性将包含在所生成的YAML文件中的必需属性列表中。
该库不做的一件事是将可选属性标记为nullable: true
。但是,默认情况下,Spring Boot应用程序将接受请求中的null
,并在可选属性的响应中返回null
。这意味着OpenAPI文档和端点的行为之间存在差异。
手动将任何单个属性标记为可为空很简单:只需将@Schema(nullable = true)
添加到字段或访问器即可。但是,在具有多个属性的大型模型中,我希望以与required
属性相同的方式自动确定这一点。也就是说,如果该属性不是必需的,我希望它为nullable
,反之亦然。
如何在由springdoc-openapi生成的OpenAPI文档中将我的可选属性标记为nullable: true
?
示例
import io.swagger.v3.oas.annotations.media.Schema;
import javax.validation.constraints.NotNull;
public class RequiredExample {
@NotNull
private String key;
private String value;
public String getKey() { return key; }
public void setKey(String key) { this.key = key; }
public String getValue() { return value; }
public void setValue(String value) { this.value = value; }
}
生成的OpenAPI文档:
"components": {
"schemas": {
"RequiredExample": {
"required": [
"key"
],
"type": "object",
"properties": {
"key": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
}
}
所需的OpenAPI文档:
"components": {
"schemas": {
"RequiredExample": {
"required": [
"key"
],
"type": "object",
"properties": {
"key": {
"type": "string"
},
"value": {
"type": "string"
"nullable": true
}
}
}
}
}
发布于 2021-09-23 22:39:58
一种解决方案是创建一个springdoc-openapi OpenApiCustomiser
Spring bean,它将所有属性设置为nullable
,除非它们在required
属性列表中。这种方法得益于内置的springdoc-openapi对@NotNull
和其他此类注释的支持,因为required
属性将根据这些属性的存在以标准方式进行计算。
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.OpenApiCustomiser;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class NullableIfNotRequiredOpenApiCustomizer implements OpenApiCustomiser {
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public void customise(OpenAPI openApi) {
for (Schema schema : openApi.getComponents().getSchemas().values()) {
if (schema.getProperties() == null) {
continue;
}
((Map<String, Schema>) schema.getProperties()).forEach((String name, Schema value) -> {
if (schema.getRequired() == null || !schema.getRequired().contains(name)) {
value.setNullable(true);
}
});
}
}
}
https://stackoverflow.com/questions/69310598
复制相似问题