Spring Boot 数据验证简介

简述

在软件开发过程中,经常遇到验证属性的合法性.在未使用标签验证的情况下,会使用大量的if语句校验数据的合法性.如

if (StringUtils.isEmpty(user.getUserName())) {
    throw new RuntimeException("参数异常");
}
if (StringUtils.isEmpty(user.getEmail())) {
    throw new RuntimeException("参数异常");
}
if (!StringUtil.isValid(user.getEmail())) {
    throw new RuntimeException("非法的邮件地址");
}
if (user.getAge() < 18 && user.getAge() > 100) {
    throw new RuntimeException("非法年龄");
}
if (!"enable".equals(user.getUserStatus())&&!"disable".equals(user.getUserStatus())){
    throw new RuntimeException("user_status 值范围是 enable,disable");
}

这种代码不仅是比较罗嗦,同时不利于扩展,每次判断逻辑中都会添加大量的判断代码,可读性比较低下.
为了解决类似问题,Bean Validation就出现了.
Bean Validation 为 JavaBean 验证定义了相应的元数据模型和 API.缺省的元数据是 Java Annotations,通过使用 XML 可以对原有的元数据信息进行覆盖和扩展.在程序中,通过使用 Bean Validation 或是自己定义的 constraint,例如 @NotNull, @Max, @Flag, 就可以确保数据模型(JavaBean)的合法性.
Bean Validation 是一个运行时的数据验

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章