Cannot Autowired a dependency into customized validator
Asked Answered
G

2

2

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;
    }
}
Goodsized answered 22/11, 2021 at 12:28 Comment(3)
You will need to add code so that we can help you. Thanks!Ewart
Validators need to be instantiable by the validation framework (Hibernate Validator here), and they're not Spring beans, so autowiring generally isn't available. If you explain your validation concept, we might be able to help. (Note also that if you're using Lombok with Spring beans, you can just use @RequiredArgsConstructor; @Autowired is not required if you only have a single constructor.)Ackerman
..but i think it is still feasible/possible/easy ;) (i will test, before answer:)Antarctic
A
0

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.

Antarctic answered 22/11, 2021 at 16:19 Comment(0)
W
0

everyones' case may be different, mine was @Configuration files

please refer to comment by Claudiu

make sure your beans return javax Validator

Woll answered 29/11, 2022 at 0:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.