Fabio Ebner
Fabio Ebner

Reputation: 2783

Hibernate Validate Object inside ConstraintValidator with Spring boot

I create one field-level-constraint just like this example https://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-usingvalidator.html#d0e281 and put then in my field that is an object

public classe Car {

  @validateEngine
 private Engine engine;
 ...
}

my Engine class:

public class Engine {
   @ValidadeEngineName
   private String name;
   @NotNull
   private Integer size;
}

It`s possible to in my validateEngineImpl

 public class validateEngineImpl implements ConstraintValidator<validateEngine, String> {



        @Override
        public void initialize(validateEngine constraintAnnotation) {
            System.out.println("s");
        }

        @Override
        public boolean isValid(Engine value, ConstraintValidatorContext context) {
            if(value == null){
    return true;
    }else{
       //HERE I NEED TO execute one validation in engine, 
but I want to use the annotations, something like 
Validator.valide(value), or I need to validate one by one? Strings.isNullOrEmpty(value.getName())....
        }
    }

Using the code from @Hervian, works but in my validateEngineNameImpl I lost the @Autowired

public class validateEngineNameImpl implements ConstraintValidator<validateEngineName, String> {

    @Autowired
    private MyService myService;

    @Override
    public void initialize(validateEngine constraintAnnotation) {
        System.out.println("s");
    }

    @Override
    public boolean isValid(Engine value, ConstraintValidatorContext context) {
       //Here my myService are not autowired
    }

}

Its possible dont lost the @Autowired, or pass somethig to my validateEngineNameImpl from validateEngineImpl?

Upvotes: 1

Views: 1265

Answers (1)

Hervian
Hervian

Reputation: 1076

In your Car class, simply annotate the Engine field with @Valid.

Then, calling:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Car>> set = validator.validate(car);

will "go into" the engine instance and validate the various annotated fields against their ConstraintValidators.

Try it out - set the size attribute to null fx. You should get a non-empty set of ConstraintViolations.

Upvotes: 1

Related Questions