krypto88
krypto88

Reputation: 211

SpringBoot with Jakarta Validation Api not validating with @Valid Annotation

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 :)

Upvotes: 10

Views: 49011

Answers (2)

Gerardo Cauich
Gerardo Cauich

Reputation: 632

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.

Upvotes: 20

ifu25
ifu25

Reputation: 71

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

use javax.* not jakarta.*

Upvotes: 7

Related Questions