2

I have the following custom hibernate validator in a application build with spring boot 2.1.5.

public class MyValidator implements ConstraintValidator<MyValidAnnotation, DTO> {
    @Autowired
    private MyBean myBean;

     @Override
    public boolean isValid(DTO dto, ConstraintValidatorContext constraintValidatorContext) {
        // logic
    }
}

I need to use this validator in 2 cases, in isValid method I need to skip some checkings. I found a solution to set a parameter on ConstraintValidatorContext with the following code:

HibernateValidatorFactory hibernateValidatorFactory = Validation.buildDefaultValidatorFactory()
                .unwrap( HibernateValidatorFactory.class );

Validator validator = hibernateValidatorFactory.usingContext()
                .constraintValidatorPayload(RepairEstimateDTO.class.getSimpleName())
                .getValidator();

validator.validate(dto);

The problem is that MyBean isn't injected, in isValid method myBean is null.

How can I reuse this validator in 2 contexts without code duplication?

Thanks

Dorin
  • 2,167
  • 4
  • 20
  • 32

1 Answers1

0

I think this piece of code will solve your problem:

@Bean
public Validator validator ( AutowireCapableBeanFactory autowireCapableBeanFactory) {

    ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
        .configure().constraintValidatorFactory(new SpringConstraintValidatorFactory(autowireCapableBeanFactory))
        .buildValidatorFactory();
    Validator validator = validatorFactory.getValidator();

    return validator;
}

Copied from: Autowired gives Null value in Custom Constraint validator

Alexander Petrov
  • 9,204
  • 31
  • 70
  • Thanks for your response, this solved the problem with injections of the bean.. Using this solution how can I use the same validator for 2 separate contexts? (e.g. I want to skip some logic from isValid method if I do the call from Service1 and leave the logic as it is for service2 ) – Dorin Apr 03 '20 at 15:34