1.定义注解
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = {RelationValueValidator.class})
public @interface RelationValue {
/**默认错误消息*/
String message() default "必须为指定值";
//分组
Class<?>[] groups() default {};
//负载
Class<? extends Payload>[] payload() default {};
}
2.实现自定义注解
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.Map;
public class RelationValueValidator implements ConstraintValidator<RelationValue, Object> {
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Map<String, Object> fieldValMap = this.getFieldValMap(value);
Integer strategyStatus = (Integer)fieldValMap.get("targetStatus");
if (null != strategyStatus) {
if (strategyStatus > 0) {
Integer targetScopeStart = (Integer)fieldValMap.get("targetStart");
Integer targetScopeEnd = (Integer)fieldValMap.get("targetEnd");
if (targetScopeStart < 1 || targetScopeEnd < 1) {
return false;
}
}
}
return true;
}
/**
* 获取自定义类型字段
*
* @param obj
* @return
*/
private Map<String, Object> getFieldValMap(Object obj) {
HashMap<String, Object> fieldValMap = Maps.newHashMap();
Class<?> clz = obj.getClass();
try {
PropertyDescriptor strategyStatus = new PropertyDescriptor("targetStatus", clz);
PropertyDescriptor targetStart = new PropertyDescriptor("targetStart", clz);
PropertyDescriptor targetEnd = new PropertyDescriptor("targetEnd", clz);
fieldValMap.put("targetStatus", strategyStatus.getReadMethod().invoke(obj));
fieldValMap.put("targetScopeStart", targetStart.getReadMethod().invoke(obj));
fieldValMap.put("targetScopeEnd", targetEnd.getReadMethod().invoke(obj));
} catch (Exception e) {
e.printStackTrace();
}
return fieldValMap;
}
}
3.请求参数VO
@Data
@NoArgsConstructor
@AllArgsConstructor
public class GoodsAddDto {
@Valid
@NotNull(message = "子商品列表不能为空!")
@Size(min = 1, message = "子商品列表不能为空!")
@ApiModelProperty(value = "子商品列表")
List<GoodsSubEntity> goodsSubs;
}
@RelationValue(message = "起-终位置必须大于1")
@ApiModel(value = "子商品对象", description = "子商品表")
public class GoodsSubEntity {
@ApiModelProperty(value = "策略状态(0:关闭;1:开启)")
private Integer targetStatus;
@ApiModelProperty(value = "目标范围-起")
private Integer targetStart;
@ApiModelProperty(value = "目标范围-止")
private Integer targetEnd;
}
|