0

Autowiring works everywhere in application except inside this custom validation annotation class where it is null when called from inside isValid() method.

javax.validation:validation-api: 2.0.1.Final
org.hibernate:hibernate-validator: 5.0.1.Final
spring: 5.1.4.RELEASE


@Component
public class ValidatorUniqueUsername implements ConstraintValidator<UniqueUsername, String> {
    @Autowired
    AccountService jpaAccountService;

    @Override
    public void initialize(UniqueUsername constraintAnnotation) { }

    @Override
    public boolean isValid(String username, ConstraintValidatorContext context) {
        return username != null && jpaAccountService.findByUsername(username) == null;
    }
}


@Entity
...
public class Account extends BaseEntity<Long> implements Serializable{
    @NotEmpty
    @UniqueUsername
    private String username;
}

@Configuration
    public class AppConfig implements AsyncConfigurer {
@Bean
public Validator validatorFactory() {
    return new LocalValidatorFactoryBean();
}
        @Bean
        public static LocalValidatorFactoryBean validatorFactory() {
            return new LocalValidatorFactoryBean();
        }
Jamie White
  • 1,560
  • 3
  • 22
  • 48

1 Answers1

0

Your custom annotation @UniqueUsername instantiates and calls your ValidatorUniqueUsername but it does not inject it even it is annotated with @Component.

And because of this none of the resources to be autowired in your ValidatorUniqueUsername will be injected.

You could try to add this to your @Configuration:

@Bean
public Validator validatorFactory() {
    return new LocalValidatorFactoryBean();
}

See more here (excerpt below):

In spring if we register LocalValidatorFactoryBean to bootstrap javax.validation.ValidatorFactory then custom ConstraintValidator classes are loaded as Spring Bean. That means we can have benefit of Spring's dependency injection in validator classes.

pirho
  • 11,565
  • 12
  • 43
  • 70
  • @JamieWhite I remember I had this working few days ago but I'll look at better time if there is some other conf that you are missing. – pirho Mar 22 '19 at 08:14