0

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?

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This make sense because javax Validation is not a Spring native function, but it is well integrated with the framework
it is not native, but the object is created by spring

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.