OAS ignoring @Schema(required=false) on property if it marked as @NotNull

Viewed 57

I have model with field i want to make not required:

import io.swagger.v3.oas.annotations.media.Schema;

import javax.validation.constraints.NotNull;

public class Model {
    @NotNull
    @Schema(required = false)
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

but springdoc automaticaly marks it as required(i know that it's cause of @NotNull annotation)

 "schemas": {
      "Model": {
        "required": [
          "name"
        ],
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          }
        }
      },

So how i can make field not required in generated documentation and leave both annotations i mean @NotNull and @Schema?

Used dependencies:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.7</version>
</dependency>
1 Answers

You can override the @NotNull annotation using ParameterCustomizer like this:

@Component
public class ParameterCustomizer implements org.springdoc.core.customizers.ParameterCustomizer {

    @Override
    public Parameter customize(Parameter parameterModel, java.lang.reflect.Parameter parameter, HandlerMethod handlerMethod) {
        NotNull annotation = parameter.getAnnotation(NotNull.class);
        if (annotation != null) {
            parameterModel.required(false);
        }
        return parameterModel;
    }
}
Related