jahoza
jahoza

Reputation: 49

Spring Boot custom constraint validation component

config class

@ComponentScan(basePackages = {"validator"})
class AppConfiguration { ... }

annotation class

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueLoginValidator.class)
public @interface UniqueLogin {
    String message() default "{com.dolszewski.blog.UniqueLogin.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

validator class

@Component
class UniqueLoginValidator implements ConstraintValidator<UniqueLogin, String> {

    private UserRepository userRepository;

    public UniqueLoginValidator(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void initialize(UniqueLogin constraint) {
    }

    public boolean isValid(String login, ConstraintValidatorContext context) {
        return login != null && !userRepository.findByLogin(login).isPresent();
    }

}

I have a class with property @UniqueLogin String login, I also use other annotations like @Size and @Max, the last 2 works, but my custom annotation does not work.

Can you please help to understand why spring do not call custom validator?

Upvotes: 0

Views: 2150

Answers (2)

Javad Mahdioun
Javad Mahdioun

Reputation: 370

Here are a few points to help clarify the issue.

  • The @Component annotation is not required for the UniqueLoginValidator class.
  • Using the @Override annotation on the isValid method is recommended for clarity and to ensure proper method overriding.
  • Using ElementType.PARAMETER is advisable for validation in your RestController methods, as it enhances clarity and ensures that annotations are applied directly to method parameters.

enter image description here

enter image description here

Upvotes: 0

Roberto Canini
Roberto Canini

Reputation: 349

It worked for me to create inside src/main/resources/META-INF/services a file named javax.validation.ConstraintValidator with a list new line separated of all qualified name of custom constraint validators you created.

This way, Spring will automatically register the custom validator.

This file will be automatically checked from Spring and included into built artifact.

Be careful of annotation configuration after applying this solution. You should annotate with @Constraint(validatedBy = { }) to prevent double validator initialization.

Upvotes: 2

Related Questions