基于JSR-303做轮子,自定义起始日期校验

近几年Spring Boot越来越普及,Spring Boot支持JSR-303验证框架,可以自定义自己的校验规则简化开发,因为是编写一个通用的校验,所以公司业务开发上,首先要同一每个Bean的校验字段

pom.xml


        org.springframework.boot
        spring-boot-starter-parent
        1.5.6.RELEASE
    
     
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            junit
            junit
        
        
            junit
            junit
        
    

Bean

package com.jsrtest.po;

import com.jsrtest.annotation.JsrAnnotation;

import java.util.Date;

/**
 */
@JsrAnnotation
public class DatePO {
    private Date startDate;
    private Date endDate;

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }
}

如果要通用类需要保证校验的日期字段命名同一

JsrAnnotation

package com.jsrtest.annotation;

import com.jsrtest.validated.CustomValidator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 */
@Target({ElementType.TYPE,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = CustomValidator.class)
public @interface JsrAnnotation {
    String message() default "开始时间大于结束时间";
    Class[] groups() default {};
    Class[] payload() default {};
}

@Constraint:声明使用什么类进行验证

验证必须要提供的字段信息

 message:用于创建错误信息
 groups:验证规则分组

 payload:定义验证有效负荷(暂时没用过)

CustomValidator

package com.jsrtest.validated;

import com.jsrtest.annotation.JsrAnnotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;

/**
 */
public class CustomValidator implements ConstraintValidator {


    @Override
    public void initialize(JsrAnnotation constraintAnnotation) {

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        Class currentClass = value.getClass();
        try {
            Method getStartDate = currentClass.getMethod("getStartDate");
            Date startDate = (Date)getStartDate.invoke(value);
            Method getEndDate = currentClass.getMethod("getEndDate");
            Date endDate = (Date)getEndDate.invoke(value);
            return startDate.getTime()<=endDate.getTime();
        }  catch (Exception e) {
            return false;
        }
    }


}

value为当前进行校验的对象实例,通过使用反射来获得这个对象,前文所提及的字段名同一是为了作为通用的校验注解需要让该注解适用于所有bean,通过使用反射调用方法可以获得对象的开始和结束日期,通过比较返回结果

测试类

import com.jsrtest.po.DatePO;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

/**
 */
public class mainTest {
    @Test
    public  void test1()
    {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        DatePO date=new DatePO();
        Date currentDate=new Date();
        date.setStartDate(currentDate);
        Calendar calendar=Calendar.getInstance();
        calendar.setTimeInMillis(currentDate.getTime()-1);
        date.setEndDate(calendar.getTime());
        Set> validate = validator.validate(date);
        for(ConstraintViolation result:validate)
        {
            System.out.print(result.getMessage());
        }
    }
}

结果返回:开始时间大于结束时间


参考资料:http://blog.csdn.net/singno_java/article/details/32920647

你可能感兴趣的:(功能实现)