使用Spring引导

时间:2016-04-02 13:31:21

标签: java spring hibernate spring-boot hibernate-validator

我创建了一个字段级约束,就像这个示例https://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/validator-usingvalidator.html#d0e281一样,然后放在我的字段中作为对象

public classe Car {

  @validateEngine
 private Engine engine;
 ...
}

我的引擎课程:

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

可以在我的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())....
        }
    }

使用@Hervian中的代码,但在我的validateEngineNameImpl中工作,我丢失了@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
    }

}

s possible don丢失了@Autowired,或者从validateEngineImpl传递给我的validateEngineNameImpl吗?

1 个答案:

答案 0 :(得分:1)

在您的Car类中,只需使用@Valid注释Engine字段。

然后,致电:

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

将“进入”引擎实例并根据ConstraintValidators验证各种带注释的字段。

尝试一下 - 将size属性设置为null fx。你应该得到一组非空的ConstraintViolations。