Notice:本文对Validation api的使用主要是运用了Hibernate-Validator,其中Hibernate-Validator是validation-api的官方扩展,使用的pom如下:
org.hibernate
hibernate-validator
5.2.4.Final
基于XML的校验
validation-api支持Java Bean和校验脱离,就是可以不在一起,这点方便Api定义者可以Java Bean,但是不添加校验功能,而实现者能够针对Java Bean的定义来决定是否需要校验
例如,
数据模型:
public class OrderBaseModel {
public long id;
public String buyerCbAccoutId;
public String sellerCbAccoutId;
public OrderSatusEnum status;
public String buyerCompanyName;
public String sellerCompanyName;
public String buyerBizPhone;
public String sellerBizPhone;
public List offers = new ArrayList<>();
public String pickType;
public List receiveAddressGroups = new ArrayList<>();
public String message;
public double discountFee;
public double additionalFee;
public String payway;
public long payTimeout;
public Long autoConfirmReceipt;
public long appointedArrivalDate;
....get/set
}
校验逻辑:
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.1.xsd"
xmlns="http://jboss.org/xml/ns/javax/validation/mapping" version="1.1">
//指定校验模型
com.alibaba.cb.api.order.model
//Class级别校验,并设置忽略注解的校验逻辑
//支持jexl表达式的校验逻辑
{com.alibaba.cb.api.order.model.ordermodel.receiveAddressGroups}
jexl
// 这里如果不设置别名,_this指的是当前class的实例对象,可以取到任何一个对象中的属性值进行联动校验
if(_this.pickType=='push' and size(_this.receiveAddressGroups) > 2){
return false;
}else if(_this.pickType=='pull' and size(_this.receiveAddressGroups) > 10){
return false;
}else if(size(_this.receiveAddressGroups) == 0) {
return false;
}
return true;
{com.alibaba.cb.api.order.model.ordermodel.buyerCbAccoutId}
{com.alibaba.cb.api.order.model.ordermodel.buyerCompanyNameSize}
20
// 支持正则校验逻辑
{com.alibaba.cb.api.order.model.ordermodel.sellerBizPhonePattern}
^(|[0-9]{1,11})$
{com.alibaba.cb.api.order.model.ordermodel.offers}
1
{com.alibaba.cb.api.order.model.ordermodel.pickType}
{com.alibaba.cb.api.order.model.ordermodel.discountFeeMin}
0
{com.alibaba.cb.api.order.model.ordermodel.discountFeeDigits}
6
2
{com.alibaba.cb.api.order.model.ordermodel.additionalFeeMin}
0
{com.alibaba.cb.api.order.model.ordermodel.additionalFeeDigits}
6
2
{com.alibaba.cb.api.order.model.ordermodel.payway}
{com.alibaba.cb.api.order.model.ordermodel.payTimeoutNotNull}
//支持javascript表达式
{com.alibaba.cb.api.order.model.ordermodel.payTimeoutScript}
javascript
_this > new Date().getTime()
{com.alibaba.cb.api.order.model.ordermodel.autoConfirmReceiptMin}
5
从以上来看,xml其实就是annotation的另外一个翻版,但是意义却比较大,可以实现定义和校验实现分离
实施:
Configuration> config = Validation.byDefaultProvider().configure();
//对于xml文件
config.addMapping(new FileInputStream(validationFile));
基于annotation的校验
暂无