1

How can I disable JSR-303 annotation processing in springdoc for specific fields?

I have the following request class MyRequestTO where the field name is actually optional. The @NotBlank annotation is only applied to the unwrapped JsonNullable. This means the user is allowed to omit the field when sending MyRequestTO but if set it must not be blank. However the open api doc marks the name field as required. Changing the @Schema annotation to @Schema(type = "string", required = false) does not help.

I want to avoid a solution where I have to write my own annotation and make use of org.springdoc.core.customizers.OpenApiCustomiser. The desired solution should also work for other types like JsonNullable<Boolean> annotated with @NotNull.

public class MyRequestTO {

    @Schema(type = "string")
    @NotBlank
    private JsonNullable<String> name = JsonNullable.undefined();

    public JsonNullable<String> getName() {
        return name;
    }

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

Relevant dependencies

implementation "org.openapitools:jackson-databind-nullable:0.2.1"
implementation "org.springdoc:springdoc-openapi-ui:1.5.5"
christopher.online
  • 2,614
  • 3
  • 28
  • 52

2 Answers2

0

This is not working as @NotBlank allow null values

The @NotNull class isValid() method is called after the @NotBlank class isValid(), hence forbidding null values.

So you can try with @Pattern with validation of not black string as follows :

@Pattern(regexp = "/^$|\\s+/")
String name

This will allows not null values but not allow empty string

Ajinkya
  • 325
  • 3
  • 12
  • Thank you for trying but it is not really what I am looking for. First of all, this suggestion was already made in the comments below my question. Second, I am looking for a way to disable the processing of those annotations. The desired solution should also work for other types like `JsonNullable` annotated with `@NotNull`. Maybe I should have clarified that better. – christopher.online Apr 01 '21 at 09:53
0

@crizzis solution from the comments to my question works as expected. Fields are no longer marked as required but if supplied have to conform to the annotation constraints.

The JSR-303 (e.g. @NotBlank or @NotNull) annotation belongs in front of the type parameter:

private JsonNullable<@NotBlank String> name = JsonNullable.undefined();
private JsonNullable<@NotNull Boolean> enabled = JsonNullable.undefined();

Then the resulting openAPI docs will mark the fields as "required" : false.

christopher.online
  • 2,614
  • 3
  • 28
  • 52