多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# Hibernate 验证器 CDI – `@HibernateValidator`示例 > 原文: [https://howtodoinjava.com/hibernate/hibernate-validator-cdi/](https://howtodoinjava.com/hibernate/hibernate-validator-cdi/) 注入默认 Java bean 验证类实现的 Hiberate 验证器 CDI 的 Java 示例。 `javax.validation.ValidatorFactory`和[`javax.validation.Validator`](https://docs.oracle.com/javaee/7/api/javax/validation/Validator.html)具有`hibernate-validator-cdi`依赖项。 如果应用具有多个[`org.hibernate.validator.cdi.HibernateValidator`](https://docs.jboss.org/hibernate/validator/5.1/api/org/hibernate/validator/cdi/HibernateValidator.html)之类的验证器实现,还应该学习注入专门的验证器。 请注意,如果您的应用在开箱即用的环境中运行,那么您无需添加其他依赖项即可运行此示例。 例如,Spring 框架隐式提供了此类 CDI 基础结构,因此请不要在 Spring 框架中使用 [Hiberate 验证器 CDI](http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-integration-with-cdi) 。 对于其他应用,例如独立的 Java 应用,可能需要它才能使用注解创建`HibernateValidator`。 ## 1\. Hibernate 验证器 CDI Maven 依赖项 下面列出了与 Hiberate 验证器一起使用的所有必需依赖项。 ```java <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>com.howtodoinjava.example</groupId> <artifactId>hibernate-validator</artifactId> <version>0.0.1</version> <packaging>jar</packaging> <name>hibernate-validator</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.11.Final</version> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator-cdi</artifactId> <version>6.0.11.Final</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>3.0.1-b06</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.6</version> </dependency> </dependencies> </project> ``` ## 2\. 带有验证注解的模型类 一个带有字段验证注解的简单 Java 类。 ```java package com.howtodoinjava.example.model; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class User { @NotNull(message = "Please enter id") private Long id; @Size(max = 20, min = 3, message = "{user.name.invalid}") @NotEmpty(message = "Please enter name") private String name; @Email(message = "{user.email.invalid}") @NotEmpty(message = "Please enter email") private String email; public User(Long id, String name, String email) { super(); this.id = id; this.name = name; this.email = email; } //Getters and Setters @Override public String toString() { return "User [id=" + id + ", name=" + name + ", email=" + email + "]"; } } ``` ## 3\. 注入默认的和 Hiberate `javax.validation.Validator` 使用`@Inject`注解注入`ValidatorFactory`和`Validator`。 注入的 Bean 是默认的验证器工厂实例和验证器实例。 ```java @Inject private static ValidatorFactory validatorFactory; @Inject private static Validator validator; ``` 如果您正在使用多个 Bean 验证供应器,则可以通过使用`@HibernateValidator`限定符注解注入点来确保注入了 Hibernate 验证器的工厂和验证器。 ```java import org.hibernate.validator.cdi.HibernateValidator; @Inject @HibernateValidator private static ValidatorFactory validatorFactory; @Inject @HibernateValidator private static Validator validator; ``` ## 4\. 如何验证 bean 使用注入的验证器验证 Java Bean 和检查错误消息的示例。 ```java package com.howtodoinjava.example; import java.util.Set; import javax.inject.Inject; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.hibernate.validator.cdi.HibernateValidator; import com.howtodoinjava.example.model.User; public class TestHibernateValidator { @Inject @HibernateValidator private static ValidatorFactory validatorFactory; @Inject @HibernateValidator private static Validator validator; public static void main(String[] args) { //Create ValidatorFactory which returns validator validatorFactory = Validation.buildDefaultValidatorFactory(); //It validates bean instances validator = validatorFactory.getValidator(); User user = new User(null, "1", "abcgmail.com"); //Validate bean Set<ConstraintViolation<User>> constraintViolations = validator.validate(user); //Show errors if (constraintViolations.size() > 0) { for (ConstraintViolation<User> violation : constraintViolations) { System.out.println(violation.getMessage()); } } else { System.out.println("Valid Object"); } } } ``` 程序输出: ```java Aug 06, 2018 12:25:17 PM org.hibernate.validator.internal.util.Version <clinit> INFO: HV000001: Hibernate Validator 6.0.11.Final Please enter id '1' is an invalid name. It must be minimum 3 chars and maximum 20 chars. Invalid Email ``` 上面的示例[从类路径中的属性文件中获取资源消息](https://howtodoinjava.com/hibernate/hibernate-validator-java-bean-validation/)。 ```java user.name.invalid='${validatedValue}' is an invalid name. It must be minimum {min} chars and maximum {max} chars. user.email.invalid=Invalid Email ``` ## 5\. 总结 在上面的示例中,我们学习以下内容: * 我们如何包含 Hiberate 验证器 CDI 依赖项并使用它。 * 如何注入默认的验证器工厂和验证器实例。 * 如果存在多个 Java Bean 验证程序实现,则如何注入专用的验证程序工厂实例和验证程序实例。 例如,在上述情况下,它是 Hiberate 验证器。 * 如何使用注解配置来验证 Java Bean。 学习愉快!