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;
    }
}
Rio85
  • 83
  • 7
  • 1
    You will need to add code so that we can help you. Thanks! – João Dias Nov 22 '21 at 12:59
  • 4
    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.) – chrylis -cautiouslyoptimistic- Nov 22 '21 at 13:34
  • ..but i think it is still feasible/possible/easy ;) (i will test, before answer:) – xerx593 Nov 22 '21 at 13:52

2 Answers2

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.

xerx593
  • 12,237
  • 5
  • 33
  • 64
0

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

please refer to comment by Claudiu

make sure your beans return javax Validator

RMDaw
  • 86
  • 1
  • 1