我尝试使用hibernate validator编写非常简单的应用程序:
我的步骤:
在pom. xml中添加了以下依赖项:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.1.Final</version>
</dependency>
写了以下代码:
class Configuration {
Range(min=1,max=100)
int threadNumber;
//...
public static void main(String[] args) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Configuration configuration = new Configuration();
configuration.threadNumber = 12;
//...
Set<ConstraintViolation<Configuration>> constraintViolations = validator.validate(configuration);
System.out.println(constraintViolations);
}
}
我得到以下堆栈跟踪:
Exception in thread "main" javax.validation.ValidationException: Unable to instantiate Configuration.
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:279)
at javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:110)
...
at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:110)
at org.hibernate.validator.internal.engine.ConfigurationImpl.<init>(ConfigurationImpl.java:86)
at org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:41)
at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:276)
... 2 more
我做错了什么?
它在添加到pom. xml
以下依赖项后工作:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
Hibernate Validator入门:
Hibernate Validator还需要统一表达式语言(JSR 341)的实现来评估违反约束消息中的动态表达式。当您的应用程序在JavaEE的容器(如WildFly)中运行时,容器已经提供了EL实现。然而,在JavaSE的环境中,您必须将实现作为依赖项添加到POM文件中。例如,您可以添加以下两个依赖项来使用JSR 341引用实现:
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.4</version>
</dependency>
只做
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>2.2.4</version>
</dependency>
如果您不需要javax. el(例如在JavaSE应用程序中),请使用Hibernate validator中的ParameterMessageInterpolator。Hibernate validator是一个独立的组件,可以在没有Hibernate本身的情况下使用。
依赖于Hibernate验证器
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
使用ParameterMessageInterpolator
import javax.validation.Validation;
import javax.validation.Validator;
import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
private static final Validator VALIDATOR =
Validation.byDefaultProvider()
.configure()
.messageInterpolator(new ParameterMessageInterpolator())
.buildValidatorFactory()
.getValidator();