javabean 注解验证工具类

本文介绍了如何使用Java BeanValidator进行对象验证,展示了如何创建ValidatorFactory和Validator实例,以及validate方法的应用。CebPubTransfer类中的字段验证规则被详细展示,包括NotEmpty和ByteLength注解的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值