Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot custom constraint validator not injected with service

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.

like image 892
Greyshack Avatar asked Aug 20 '15 19:08

Greyshack


1 Answers

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

like image 165
Michael Kowalski Avatar answered Nov 15 '22 02:11

Michael Kowalski