Cannot Autowired a dependency into customized validator

Viewed 428

I'm looking to validate my object properties using customized validators, and i need to inject some beans. So i can't autowire any beans and i get this exception :

java.lang.NoSuchMethodException: com.*.*.MyValidatorValidator.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3517)
    at java.base/java.lang.Class.getConstructor(Class.java:2238)
    at org.hibernate.validator.internal.util.privilegedactions.NewInstance.run(NewInstance.java:41)
    ... 110 common frames omitted

How can success Autowire a beans ?

@Slf4j
@RequiredArgsConstructor
public class MyValidator implements ConstraintValidator<ValidMapper, String> {
    
    private MyService myService;
  
    @Autowired
    public MyValidator(MyService myService) {
        this.myService= myService;
    }
    @Override
    public boolean isValid(String valueToValid, ConstraintValidatorContext context) {  
        // Some code using MyService
        return true;
    }
}
1 Answers

Sounds correct, @chrylis-cautiouslyoptimistic- , but still worth a try (why could a "validator" not be "spring managed"!?;)

I tried a workaround (of your original error message) by: omitting constructor injection and using field injection - It worked!

But the core problem/fix is (generally):


To use @Autowired, the referencing object has to be "spring managed"!


So:

  • or declaring:

    @Component // this enables `@Autowried` on this class
    //@Scope("request") makes also sense on this type of "bean"
    public class MyValidator ...
    
  • or initializing in (one of) your application configuration(s):

    @Bean // this enables `@Autowried` on this ..
    @Scope("request")
    public MyValidator myValidator() {
        MyValidator result = new MyValidator(); // ..object.
        // ... customize more ...
        return result;
    }
    

(leaving everything as it is) should "fix" your problems.

Related