JSR 303 - Bean Validation 直接调用api的使用_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JSR 303 - Bean Validation 直接调用api的使用

JSR 303 - Bean Validation 直接调用api的使用

 2014/5/23 16:10:34  hbjava1985  程序员俱乐部  我要评论(0)
  • 摘要:packagecom.chinacache.entity;importjava.util.Set;importjavax.validation.ConstraintViolation;importjavax.validation.Validation;importjavax.validation.Validator;importjavax.validation.ValidatorFactory;importjavax.validation.constraints.Max;importjavax
  • 标签:API 使用 JSR JS
class="java">
package com.chinacache.entity;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;

@Validated
public class Person {

    @NotNull
    private String name;
    @Min(0)
    @Max(100)
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(19999);
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Person>> validate = validator.validate(p);
        for (ConstraintViolation<Person> constraintViolation : validate) {
            System.out.println(constraintViolation.getPropertyPath());
            System.out.println(constraintViolation.getMessage());
        }
    }
}

发表评论
用户名: 匿名