0

I have spring boot project, a bean using javax validation API.

I'm trying to inject a service in my custom validator for a bean. But the service object is null.
I don't find a complete example that use Spring ConstraintValidator and i don't understand the configuration that some persons made for their integration tests in another topics.

I want to have a validator with constructor injection like this (i don't want to use @Autowired nore javax @Inject) :

@Component
public class CustomValidator implements ConstraintValidator<ValidCustomValidator, CustomObj> {

private ErreurService erreurService;

public CustomValidator(ErreurService erreurService) {
     this.erreurService=erreurService;
}

@Override
public boolean isValid(CustomObj customObj, ConstraintValidatorContext context) {
    erreurService.getMessages("");
    return false;
}
}

** ErreurService**

@Service("ErreurService")
@Transactional
public class ErreurServiceImpl implements ErreurService {//...}

With this approach i got an Exception HV000064: Unable to instantiate ConstraintValidator

I try something with @Autowired but got always got a NPE. Can you help me please ?

Nozomi
  • 56
  • 4
  • you are using `ErreurService` that is never handled and injected by spring, You must use the `@Autowired' annotation or on the constructor or on the property. If on property, yuo can remove the constructor param – Angelo Immediata Sep 11 '20 at 14:11
  • I update the question. `ErreurService` is managed by Spring i have no problem injecting it in others `@services` using constructor injection – Nozomi Sep 11 '20 at 14:16
  • In this case I guess yuo have `@Autowired` near the constructor param; try to give a look or to post the constructor where it's all ok – Angelo Immediata Sep 11 '20 at 14:17
  • You are mixing concepts. A `ConstraintValidation` is a general purpose functionality (not related with Spring, although you can use in that framework) used to validate "generic information": a parameter, method, etc If you need to check something specifically related with `ErreurService` => create a method in that class to do it. In that way, you won't need to deal with DI. Another option is create an specific `ConstraintValidator` to check the information you want to verify (not the "whole service"). Take a look to the link https://www.baeldung.com/javax-validation-method-constraints – doctore Sep 11 '20 at 18:01

1 Answers1

0

Did you put the @Service annotation on ErreurService implementation class? Is it in the package from specified ComponentScan?

  • Yes, i did it. As you can see in piece of code `@Service` is present on the implementation and the class is scanned – Nozomi Sep 12 '20 at 06:41