SpringBoot with Jakarta Validation Api not validating with @Valid Annotation
Asked Answered
U

2

9

i have a question to Spring boot and the dependency jakarta-validation-api.

Actually i have a simple DTO which holds some properties. But this properties are not being validated when I call the REST-function within the @Valid annotation.

Can someone find my error?

A snippet of my pom.mxml dependencies:

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.0-M1</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <dependency>
    <groupId>jakarta.validation</groupId>
    <artifactId>jakarta.validation-api</artifactId>
    <version>3.0.0</version>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>

  <dependency>
    <groupId>jakarta.ws.rs</groupId>
    <artifactId>jakarta.ws.rs-api</artifactId>
    <version>3.0.0</version>
  </dependency>

My DTO class:


import jakarta.validation.Valid;

@Data
public class TestDTO implements Serializable {
    private static final long serialVersionUID = -1362258531757232654L;

    @NotEmpty(message = "Id could not be empty or null.")
    @Size(min = 36, max = 36, message = "Id must contains exactly out of 36 characters.")
    private String id;

    @Min(value = 1, message = "Page size cannot be null or <= 0.")
    private Integer page;
}

And also a snippet of the REST-Resource class where the DTO is been used in the body:

@PostMapping(path = "/")
public Integer testValidation(@Valid @RequestBody TestDTO body) {
        LOGGER.info(body);
        return 1;
    }

Actually i would think that when I call the Post-REST method that it will be validated before it will go into the method body, but actually it goes into the method body without has been validated before.

Is it due to "jakarta" dependency instead of "javax"?

Hope you can help me :)

Unwept answered 24/1, 2021 at 9:8 Comment(1)
Take a look here #66972586Pisarik
S
20

From what I understand in the Spring Boot 3.0.0 M1 Release Notes, Spring Boot 2.X does not support Jakarta EE, but support will come with Spring Boot 3.X.

  • For Spring Boot 2.X you should stick with javax.
  • For Spring Boot 3.X you should stick with jakarta.
Speckle answered 31/7, 2022 at 1:7 Comment(1)
No, it's not exactly like this. From Spring Boot 2.3.0.RELEASE, it's "jakarta" braught with "spring-boot-starter-validation", no more "javax" for validation-api : mvnrepository.com/artifact/org.springframework.boot/…Flowerless
S
7

In my case(spring boot 2.4.*). I remove jakarta.validation-api dependencies,then it works.

use javax.* not jakarta.*

Shorn answered 17/5, 2021 at 6:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.