自定义hibernate validation 注解

来源:互联网 发布:淘宝上的油画都是喷绘 编辑:程序博客网 时间:2024/05/17 10:03

最近,在做excel表格导入的时候,需要进行数据校验.
数据校验,可以发生在从excel表中取数据的过程中,也可以发生在,将excel表中的数据转为对象,在用hibernate-validation进行注定属性进行校验.
本项目是maven项目,在pom.xml文件中引入:

<dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-validator</artifactId>            <version>5.24</version></dependency>

与springMVC整合
在springmvc.xml文件中引入:

<mvc:annotation-driven validator="validator"/>

在springContent.xml中引入:

<!-- 配置 JSR303 Bean Validator 定义 --><bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

比如:

   /**     * 来源     */    @NotEmpty(message = "应急装备来源:不能为空")    @ExcelField(title = "来源")    @Length(min=0,max=255)     private String source;

hibernate-validation中常见注解的介绍参考:
http://blog.csdn.net/u011851478/article/details/51842157
hibernate-validation的自定义注解:
1:定义注解

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })@Retention(RUNTIME)@Documented@Constraint(validatedBy = { DateValidator.class })public @interface DateFiled {    String message() default "日期格式不正确,正确的格式类似于19980413";    /**     * @return the regular expression to match     */    String regexp() default "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)";    Class<?>[] groups() default { };    Class<? extends Payload>[] payload() default { };    /**     * Defines several {@code @NotEmpty} annotations on the same element.     */    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })    @Retention(RUNTIME)    @Documented    public @interface List {        NotEmpty[] value();    }

2:定义:Constraint中的validatedBy 的类,用来验证注解

public class DateValidator implements ConstraintValidator<DateFiled, Date>{     private String regexp;    @Override    public void initialize(DateFiled constraintAnnotation) {        regexp = constraintAnnotation.regexp();    }    @Override    public boolean isValid(Date value, ConstraintValidatorContext context) {        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");        if(value == null){            return true;        }        if(value != null){            String format = dateFormat.format(value);            if(format.matches(regexp)){                return true;            }        }        return false;    }}

自定义注解参考的博客:
http://blog.csdn.net/ruangong1203/article/details/51002360
说明@Target,@Retention注解作用的博客:
http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html

原创粉丝点击