Bean 是 Java Bean 的缩写,在 Java 分层架构的实际应用中,从表示层到持久化层,每一层都需要对 Java Bean 进行业务符合性验证,如图 1 所示。然而对于同一个 Java Bean 的对象,在每一层都需要实现同样的验证逻辑时,这将是一项耗时且容易诱发错误的做法。Bean Validation 规范的目标就是避免多层验证的重复性。事实上,开发者更倾向于将验证规则直接放到 Java Bean 本身,使用注解的方式进行验证规则的设计。
项目架构
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Test</groupId> <artifactId>vi</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>vi</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.3.Final</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>el-api</artifactId> <version>1.0</version> </dependency> </dependencies> </project>
LoginForm.java
package com.test; 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 javax.validation.constraints.Size; public class LoginForm { @NotNull(message = "用户名不能为空") @Size(min = 2, max = 12, message = "用户长度2-12位") private String username; @NotNull(message = "密码不能为空") @Size(min = 6, max = 12, message = "密码长度6-12位") private String password; @Min(value = 18, message = "年龄最小值必须是18") @Max(value = 60, message = "年龄最大值必须是60") private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public static void main(String[] args) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); LoginForm loginForm = new LoginForm(); loginForm.setPassword("1"); Set<ConstraintViolation<LoginForm>> constraintViolations = validator.validate(loginForm); for (ConstraintViolation<LoginForm> constraintViolation : constraintViolations) { System.out.println(constraintViolation.getMessage()); } System.out.println("------"); LoginForm loginForm2 = new LoginForm(); loginForm2.setPassword("1234567"); Set<ConstraintViolation<LoginForm>> constraintViolations2 = validator.validate(loginForm2); for (ConstraintViolation<LoginForm> constraintViolation : constraintViolations2) { System.out.println(constraintViolation.getMessage()); } } }
运行结果
原文地址:http://blog.csdn.net/h348592532/article/details/45917241