I'm having issues while trying to define custom constraint validation with Spring.
My code is available on my GitHub.
Here the issue. I have an entity with a validation constraint on login:
@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@UniqueLogin
private String login;
[...]
}
Here is the annotation definition:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueLoginValidator.class)
public @interface UniqueLogin {
String message() default "{loginIsNotUnique}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And there the custom validator:
public class UniqueLoginValidator implements ConstraintValidator<UniqueLogin, String> {
@Autowired
private UserRepository userRepository;
public boolean isValid(String login, ConstraintValidatorContext context) {
return userRepository.countByLogin(login) == 0;
}
}
When I call repository.save(new User("Kim"));
, I got a NullPointerException
on the injected userRepository
of UniqueLoginValidator
.
I assume that Spring as to inject properly the custom validator, and I have to tell him. But, I don't know how. I already tried some stuff found through Stack Overflow and Google, with no luck.
Any help will be appreciate.
Caused by: java.lang.NoSuchMethodException: be.groups.sandbox.customconstraintinjection.UniqueLoginValidator.<init>()
because there is no more empty constructor. I think it may be hibernate validation that works outside of Spring context that makes the repository null. - romainbsl