How to achieve that OpenApi / Swagger considers Java validation annotions using code-first approach?

Viewed 380

I looked a lot but couldn't find any solution to my problem: It is fixed that a code-first approach is to be used and I wonder how to achieve it that OpenApi (Swagger) will consider validation annotations like @Min(), @Max(), @Size(), ... in my Java / Spring Boot appliation. Whenever I let generate to OpenApi documentation these annotations keep unconsidered; they simply are not displayed.

Currently I tried using

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.5.10</version>
</dependency>

and I tried to use the common dependency as well but it doesn't help.

The bean (tried @Min() and @Max apart from @size()):

@Data
@SuperBuilder(setterPrefix = "with")
public class ResponseBody {
    @NotNull
    @Min(value = 3)
    @Max(44)
    @Size(min = 3, max = 44)
    private String referenceMessageId;
}

The OpenApi bean:

@Bean
default OpenAPI customOpenApi() {
    return new OpenAPI()
        .info(new Info()
        .title("XXX")
        .version("1.0")
        .description("xxx"))
        .components(new Components()
            .addSchemas(ERROR_RESPONSE_SCHEMA_KEY, new io.swagger.v3.oas.models.media.Schema<>().type("object").$ref("#/components/schemas/ErrorResponseBody"))
            .addSchemas(VNB_RESPONSE_SCHEMA_KEY, new io.swagger.v3.oas.models.media.Schema<>().type("object").$ref("#/components/schemas/ResponseBody"))
            .addParameters(API_VERSION_HEADER_PARAMETER, new io.swagger.v3.oas.models.parameters.Parameter()
                .name(API_VERSION_HEADER_PARAMETER)
                .required(Boolean.TRUE)
                .allowEmptyValue(Boolean.FALSE)
                .description("yyy")
                .in("header")
                .schema(new io.swagger.v3.oas.models.media.Schema<String>()
                .type("string")
                .example("1.0.0")));
1 Answers

I found out that @Min and @Max are not considered during documentation generation but @Size(min = x, max = y) is. I think it would be beneficial if Openapi implementations would consider the whole range of spring validation annotations.

Related