我想使用标准的javax.validation作为属性,并使用我自己的功能验证验证。简化的子类如下所示:
public class TestData extends AbstractData {
@NotNull
Long id = null;
@NotNull
Long value = null;
public Set<ConstraintViolation<TestData>> validateFunctional() {
Set<ConstraintViolation<TestData>> violations = new HashSet<>();
if ( id < 42 || value > 4711 ) {
//--- here comes another question: how do I create a constraint violation?
}
return violations;
}
}
这是基类:
public abstract class AbstractData {
public Set<ConstraintViolation<?>> validate() {
//--- First validate single properties
Set<ConstraintViolation<?>> violations = validator.validate( this );
}
//--- Single props OK => validate functional
if ( violations.isEmpty()) {
violations.add( validateFunctional());
}
return violations;
}
给出错误
类型不匹配:无法转换为Set&lt; ConstraintViolation&lt; AbstractData&gt;&gt;设置&lt; ConstraintViolation&lt;?&gt;&gt;
答案 0 :(得分:1)
我相信这应该是你想要的:
public abstract class AbstractData<T> {
abstract T getObj();
public Set<ConstraintViolation<T>> isValid(){
//do your custom validations if needed
return Validation.buildDefaultValidatorFactory()
.getValidator().validate(getObj());
}
}
要验证的POJO:
public class Bar extends AbstractData<Bar> {
@NotNull
private Long id;
@NotNull
private Long value;
@CustomConstraint
private Long customConstraint;
@Override
public Bar getObj() {
return this;
}
}
然后只需致电bar.isValid()
。
修改强>
关于自定义约束的问题,您可以这样做:
@Constraint(validatedBy = {CustomConstraint.CustomConstraintValidator.class})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface CustomConstraint {
String message() default "Invalid value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
class CustomConstraintValidator implements ConstraintValidator<CustomConstraint, Long> {
@Override
public void initialize(CustomConstraint customConstraint) {
}
@Override
public boolean isValid(Long obj, ConstraintValidatorContext constraintValidatorContext) {
if (obj == null)
return false;
if (obj < 10)
return false;
return true;
}
}
}
在此示例中,如果我使用@CustomConstraint
注释长字段并传递低于10的值或为null,则验证程序将返回错误,否则它将赢得错误。验证本身在示例中没用,我只是提出了一些内容作为您构建自己的片段。