This is my custom validator which checks some fields availability. The UserRepository is null, therefore the validator is not injected with it.
public class AvailableValidator implements ConstraintValidator<Available,String> {
@Autowired
private UserRepository userRepository;
private Available.Field type;
public void initialize(Available usernameAvailable) {
this.type = usernameAvailable.type();
}
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
if (userRepository == null) System.out.println("\n\n------USER REPOSITORY IS NULL-------\n\n");
switch (type){
case EMAIL:
return userRepository.findByEmail(s)==null;
case NUMBER:
return userRepository.findByNumber(s)==null;
case NAME:
return userRepository.findByName(s)==null;
default:
return false;
}
}
}
I've read on similar threads that I have to set up validator factory. I've done this:
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
@Bean
public Validator validator(){
return new LocalValidatorFactoryBean();
}
}
But it still doesn't work. userRepository is a null. Probably I got the config wrong, first time trying java configuration.
As an alternative to disabling Hibernates validation, have you tried this:
@Primary
@Bean
public Validator validator(){
return new LocalValidatorFactoryBean();
}
This would give your validator preference as suggested here.
Mike Kowalski
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With