用Annotations 给类或者类的属性加上约束(constraint),在运行期检查属性值是很优雅的.Hibernate Validator就是这样的一个框架.该框架是十分轻易的(就像参考文档中宣称的那样),几乎没有什么学习曲线,Validator 是一个验证框架 不需要和Hibernate的其他部分绑定就可以使用,只要在你的项目中添加Hibernate-annotations.jar库就可以了.那么下面就让我们看看怎么使用吧.
Person.Java 类
/*
* Created on 2006-1-12 Person.java
* @author
*/
package test.annotation.validator;
import org.hibernate.validator.Length;
import org.hibernate.validator.Min;
import org.hibernate.validator.Valid;
//@Serializability //测试自定义约束
public class Person {
private String name;
private int age;
private Address address;
public Person() {}
@Valid //注重此处
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Min(value = 1)
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Length(min = 4)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Address.java 类
/*
* Created on 2006-1-12 Address.java
* @author
*/
package test.annotation.validator;
import org.hibernate.validator.Length;
import org.hibernate.validator.Max;
import org.hibernate.validator.Min;
public class Address {
private String street;
private int num;
public Address() {}
@Min(value = 1)
@Max(value = 100)
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Length(min = 3,max = 8)
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
上面是两个用 Validator Annotations 注释的 类. 每个属性都用 约束限制了. 下面看看测试的类吧:
TestValidator.java 类
/*
* Created on 2006-1-12
* @author icerain
*/
package test.annotation.validator;
import org.hibernate.validator.ClassValidator;
import org.hibernate.validator.InvalidValue;
public class TestValidator {
public void test() {
Address add = new Address();
add.setNum(0);
add.setStreet("1");
Person p = new Person();
p.setAddress(add);
p.setAge(0);
p.setName("ice");
/******************Test validator ********/
// 注重该处只验证了Person 为了说明 @Valid 注释的使用
ClassValidator<Person> classValidator = new ClassValidator<Person> (Person.class);
InvalidValue[] validMessages = classValidator.getInvalidValues(p);
for (InvalidValue value : validMessages) {
System.out.println("InvalidValue 的长度是:" + validMessages.length
+" . 验证消息是: " + value.getMessage()
+ " . PropertyPath 是:" + value.getPropertyPath()
+" .\n\t PropertyName 是: " +value.getPropertyName()
+ "Value 是: " + value.getValue()
+" Bean 是: "+ value.getBean()
+"\n\t BeanClass 是:" + value.getBeanClass());
}
}
public static void main(String[] args) {
new TestValidator().test();
}
}