Elias Schoof
Elias Schoof

Reputation: 2046

Spring Boot & Jakarta Validation: Use group sequence by default

I am using Spring Boot 3 with Hibernate's Jakarta Validation. In my application, I have two groups of validations:

  1. Default validations
  2. Complex custom customizations that should only run if the default validations pass

I created a group sequence:

import jakarta.validation.GroupSequence;
import jakarta.validation.groups.Default;

@GroupSequence({Default.class, AllValidations.AfterDefaultValidations.class})
public interface AllValidations {

    interface AfterDefaultValidations {

    }
}

This sequence works as expected when I explicitly call it like this:

import jakarta.validation.Validator;
import org.springframework.stereotype.Component;

@Component
class MyService {
    
    private final Validator validator;

    public void myMethod(MyData data) {
        validator.validate(data, AllValidations.class);
        // ...
    }
}

However, I would like to avoid having to specify AllValidations.class every time I call validate or use the @Validated annotation. Is there a way to set this group sequence as the default, so that calling validate(data) automatically uses it?

Upvotes: 0

Views: 197

Answers (1)

Andrey Smelik
Andrey Smelik

Reputation: 1241

You can use the @GroupSequence annotation to extend the default validation scope for a given class.

For example, if you add Foo.class group

@GroupSequence({Foo.class, A.class})
class A {

  @NotNull(groups = Foo.class)
  private Long foo;
}

Then validator.validate(new A()) will check if foo is not null too.

For more information, see the Hibernate Validator Reference Guide.

Upvotes: 1

Related Questions