public class BeanValidatorUtils {
static ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
static Validator validator = vf.getValidator();
public static String validate(Object obj) {
String result = "";
Set<ConstraintViolation<Object>> set = validator.validate(obj, new Class[0]);
if (set.isEmpty())
return null;
for (ConstraintViolation<Object> cv : set)
result = result + "," + cv.getMessage();
if (!StringUtils.isBlank(result))
return result.substring(1);
return null;
}
public static void main(String[] args) {
CebPubTransfer cebPubTransfer = new CebPubTransfer();
System.out.println(validate(cebPubTransfer));
}
}
public class CebPubTransfer {
private String guid;
private String bizType;
private String bizGuid;
@NotEmpty(message = "传输模式不能为空")
@ByteLength(max = 3, message = "传输模式长度超过限制")
private String dxpMode;
@NotEmpty(message = "报文发送企业代码不能为空")
@ByteLength(max = 18, message = "报文发送企业代码长度超过限制")
private String copCode;
@NotEmpty(message = "报文发送企业名称不能为空")
@ByteLength(max = 100, message = "报文发送企业名称长度超过限制")
private String copName;
}
本文介绍了如何使用Java BeanValidator进行对象验证,展示了如何创建ValidatorFactory和Validator实例,以及validate方法的应用。CebPubTransfer类中的字段验证规则被详细展示,包括NotEmpty和ByteLength注解的使用。
290

被折叠的 条评论
为什么被折叠?



