import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = AcceptedIfValidationImpl.class)
public @interface AcceptedIf {
String fieldName();
String fieldValue();
String dependFieldName();
String dependFieldValue();
String message() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
AcceptedIf[] value();
}
}
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.lang.reflect.InvocationTargetException;
public class AcceptedIfValidationImpl implements ConstraintValidator<AcceptedIf, Object> {
private String fieldName;
private String fieldValue;
private String dependFieldName;
private String dependFieldValue;
private String message;
@Override
public void initialize(AcceptedIf constraintAnnotation) {
this.fieldName = constraintAnnotation.fieldName();
this.fieldValue = constraintAnnotation.fieldValue();
this.dependFieldName = constraintAnnotation.dependFieldName();
this.dependFieldValue = constraintAnnotation.dependFieldValue();
this.message = constraintAnnotation.message();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext ctx) {
if (value == null) {
return true;
}
try {
String fieldRealValue = BeanUtils.getProperty(value, this.fieldName);
if (!this.fieldValue.equals(fieldRealValue)) {
return true;
}
String dependRealValue = BeanUtils.getProperty(value, this.dependFieldName);
if (this.dependFieldValue.equals(dependRealValue)) {
return true;
}
if (StringUtils.isBlank(this.message)) {
ctx.disableDefaultConstraintViolation();
ctx.buildConstraintViolationWithTemplate(
this.fieldName + "字段值为:" + this.fieldValue + "时, "+ this.dependFieldName + "必须等于" + this.dependFieldValue
).addConstraintViolation();
}
return false;
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
throw new ValidationException(ex);
}
}
}