我的项目运行正常,直到我添加了hibernate-validator'在我的POM中,在@RequestBody对象的REST请求中使用@Valid功能。
我有一个NoClassDefFoundError
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/spring/app-context.xml]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javax/validation/ValidatorFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
Caused by: java.lang.NoClassDefFoundError: javax/validation/ValidatorFactory
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
... 21 more
Caused by: java.lang.ClassNotFoundException: javax.validation.ValidatorFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 35 more
我的POM是
最后一行是出现问题的那一行,我试过几个版本没有成功
答案 0 :(得分:1)
添加
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
答案 1 :(得分:0)
转到.m2存储库并删除org / hibernate / path下的文件夹。 现在清理项目并再次构建项目。这可能很好。
答案 2 :(得分:0)
上述答案都没有解决我的问题,所以我决定开发自己的验证器
新的注释界面
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) //can use in fields only.
public @interface Required {
}
一个扩展我需要验证的所有对象的基类(在Spring REST @RequestBody)
public void validate(){
Field[] fields = this.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Required.class)) {
Object value;
field.setAccessible(true);
try {
boolean fail = false;
value = field.get(this);
if (value==null){
fail = true;
}
if (value instanceof String && ((String) value).isEmpty()){
fail = true;
}
if (value instanceof List && ((List<?>) value).isEmpty()){
fail = true;
}
if (fail){
throw new PreconditionFailedException("attribute '" + field.getName() + "' cannot be empty");
}
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}