javax.validation.constraints 的注释不起作用
使用来自 javax.validation.constraints
的注释(如 @Size
、@NotNull
等)需要什么配置?这是我的代码:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Person {
@NotNull
private String id;
@Size(max = 3)
private String name;
private int age;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
当我尝试在另一个类中使用它时,验证不起作用(即创建对象时没有错误):
Person P = new Person(null, "Richard3", 8229));
为什么这不对 id
和 name 应用约束?我还需要做什么?
What configuration is needed to use annotations from javax.validation.constraints
like @Size
, @NotNull
, etc.? Here's my code:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Person {
@NotNull
private String id;
@Size(max = 3)
private String name;
private int age;
public Person(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
When I try to use it in another class, validation doesn't work (i.e. the object is created without error):
Person P = new Person(null, "Richard3", 8229));
Why doesn't this apply constraints for id
and name
? What else do I need to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
要使 JSR-303 bean 验证在 Spring 中工作,您需要做一些事情:
validation -api-1.0.0.GA.jar
(看起来你已经有了)hibernate-validator-4.1.0.Final.jar
@Valid
注释要验证的对象,然后在方法签名中包含BindingResult
以捕获错误。例子:
For JSR-303 bean validation to work in Spring, you need several things:
<mvc:annotation-driven />
validation-api-1.0.0.GA.jar
(looks like you already have that)hibernate-validator-4.1.0.Final.jar
@Valid
, and then include aBindingResult
in the method signature to capture errors.Example:
您应该使用 Validator 来检查您的类是否有效。
然后,迭代违规集合,就可以找到违规行为。
You should use Validator to check whether you class is valid.
Then, iterating violations set, you can find violations.
几年后我来到这里,多亏了 atrain 的 上面的评论。就我而言,我在接收用
@Size
注释的对象(在我的例子中为 POJO)的 API 中缺少@Valid
。它解决了这个问题。我不需要需要向用
@Size
注释的变量添加任何额外的注释,例如@Valid
或@NotBlank
code>,就是变量中的约束以及我在 API 中提到的内容...Pojo 类:
API 类:
谢谢并欢呼
I come here some years after, and I could fix it thanks to atrain's comment above. In my case, I was missing
@Valid
in the API that receives the Object (a POJO in my case) that was annotated with@Size
. It solved the issue.I did not need to add any extra annotation, such as
@Valid
or@NotBlank
to the variable annotated with@Size
, just that constraint in the variable and what I mentioned in the API...Pojo Class:
API Class:
Thanks and cheers
就我而言,我使用的是 Spring Boot 版本 2.3.0。当我将 Maven 依赖项更改为使用 2.1.3 时,它起作用了。
In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.
如果您想验证实体,则必须调用实体上的验证器。然后您将得到一组 ConstraintViolationException,它基本上显示实体的哪个字段存在约束违规以及到底是什么。也许您还可以共享一些您希望验证实体的代码。
一种常用的技术是在事务期间使用多个数据修改时在 @PrePersist 中进行验证并回滚事务,或者在收到验证异常时执行其他操作。
你的代码应该是这样的:
You would have to call a Validator on the Entity if you want to validate it. Then you will get a set of ConstraintViolationException, which basically show for which field/s of your Entity there is a constraint violation and what exactly was it. Maybe you can also share some of the code you expect to validate your entity.
An often used technique is to do validation in @PrePersist and rollback transaction if using multiple data modifications during transaction or do other actions when you get a validation exception.
Your code should go like this:
您也可以简单地将
@NonNull
与 lombok 库 一起使用,至少对于@NotNull
场景。更多详细信息:https://projectlombok.org/api/lombok/NonNull.htmlYou can also simply use
@NonNull
with the lombok library instead, at least for the@NotNull
scenario. More details: https://projectlombok.org/api/lombok/NonNull.html就我而言,原因是 hibernate-validator 版本。
可能新版本不再支持某些内容。
我改变了:
我将版本从7.0.1.Final降级到6.0.2.Final,这对我有帮助。
In my case the reason was the hibernate-validator version.
Probably something is not supported in the newer version any more.
I changed:
I downgraded the version from 7.0.1.Final to 6.0.2.Final and this helped me.
在版本 2.3.0 之后,“spring-boot-strarter-test”(包括 NotNull/NotBlank/etc)现在是“sprnig boot-strarter-validation”
只需将其从 ....-test 更改为 ...-validation 就可以了。
如果不将您使用的版本降级到 2.1.3 也可以解决该问题。
After the Version 2.3.0 the "spring-boot-strarter-test" (that included the NotNull/NotBlank/etc) is now "sprnig boot-strarter-validation"
Just change it from ....-test to ...-validation and it should work.
If not downgrading the version that you are using to 2.1.3 also will solve it.
我也面临同样的问题。 Javax 注释(@NotNull、@Valid)未执行任何验证。他们的存在并没有带来任何影响。
我必须使用“springboot-starter-validation”依赖项才能使 javax 验证有效。
这里是相关的依赖配置。另外,不要错过在要验证的对象上添加 @Valid 注释。
I also faced the same problem. Javax annotations ( @NotNull, @Valid) were not performing any validation. Their presence was not making any difference.
I have to use 'springboot-starter-validation' dependency to make the javax validations effective.
Here is the related dependencies configuration. Also don't miss to add @Valid annotation on the Object you want to validate.
您需要将@Valid添加到每个成员变量,这也是一个包含验证约束的对象。
You need to add @Valid to each member variable, which was also an object that contained validation constraints.
最近我也遇到了同样的情况。我将
hibernate-validator
升级到了 7.x 版本,但后来我注意到这个 release注意我的项目应该以 java 8 为目标,因此保留
javax.validation
而不是切换到jakarta.validation
,我不得不降级到Recently I faced the same. I upgraded
hibernate-validator
to ver 7.x but later I noticed this release noteMy project should target java 8, so keeping
javax.validation
instead of switiching tojakarta.validation
, I've had to downgrade to默认情况下,Spring 中的 javax 验证适用于 Rest 控制器方法输入变量。但为了其他地方使用相同的方法,我们必须使用 @Validated 类级别注释来注释包含 @Valid 注释的类。
我在使用 kafka 侦听器时遇到了同样的问题,之后我用 @Validated 对其进行了注释,它开始工作。
By default javax validation in spring works for Rest controller method input variables. But for other places to use the same we have to annotate class containing @Valid annotation with @Validated class level annotation.
I was facing same issue with kafka listener and after that I annotated it with @Validated it started working.
如果您使用的是 Maven,只需在 pom.xml 的 tag 下添加以下内容即可。
对于 Gradle,您可以执行以下操作。
Just add the following in your pom.xml under tag if you are using Maven.
For Gradle you can do the following.
就我而言,我有一个未调用的自定义类级约束。
一旦我向我的类添加了字段级约束(无论是自定义还是标准),类级约束就开始起作用。
对我来说似乎是错误的行为,但我想很容易解决
in my case i had a custom class-level constraint that was not being called.
as soon as i added a field-level constraint to my class, either custom or standard, the class-level constraint started working.
seems like buggy behavior to me but easy enough to work around i guess
因此,服务接口上的 @Valid 仅适用于该对象。如果您在 ServiceRequest 对象的层次结构中有更多验证,那么您可能需要显式触发验证。这就是我的做法:
如果要触发该对象的验证,则需要在对象级别具有以下注释。
So @Valid at service interface would work for only that object. If you have any more validations within the hierarchy of ServiceRequest object then you might to have explicitly trigger validations. So this is how I have done it:
You need to have following annotations at the object level if you want to trigger validation for that object.
对于方法参数,您可以使用 Objects.requireNonNull() ,如下所示:
测试(字符串str){
Objects.requireNonNull(str);
}
但这仅在运行时检查,如果为 null,则抛出 NPE。这就像先决条件检查。但这可能就是您正在寻找的。
for method parameters you can use Objects.requireNonNull() like this:
test(String str) {
Objects.requireNonNull(str);
}
But this is only checked at runtime and throws an NPE if null. It is like a preconditions check. But that might be what you are looking for.
atrain 给出了很好的答案,
但也许捕获异常的更好解决方案是利用自己的 HandlerExceptionResolver
并捕获
然后您就可以使您的处理程序尽可能保持干净。
您不再需要 myHandlerMethod 中的 BindingResult、Model 和 SomeFormBean。
Great answer from atrain,
but maybe better solution to catch exceptions is to utilize own HandlerExceptionResolver
and catch
Then you're able to keep your handler as clean as possible.
You don't need BindingResult, Model and SomeFormBean in myHandlerMethod anymore.
我最近在非常相似的情况下遇到了这个问题:
满足列出的最高评价答案的所有要求,但仍然得到错误的结果。
所以我查看了我的依赖项,发现我缺少其中一些。我通过添加缺少的依赖项来纠正它。
我正在使用 hibernate,所需的依赖项是:
*在“Spring & Hibernate 初学者”课程中拍摄的快照 @ Udemy
I came across this problem recently in a very similar situation:
Met all requirements as the top-rated answer listed but still got the wrong result.
So I looked at my dependencies and found I was missing some of them. I corrected it by adding the missing dependencies.
I was using hibernate, the required dependencies were:
*Snapshot taken in class "Spring & Hibernate for Beginners" @ Udemy
如果您使用 lombok,则可以使用 @NonNull 注释。
或者只需在 pom.xml 文件中添加 javax.validation 依赖项。
If you are using lombok then, you can use @NonNull annotation insted.
or Just add the javax.validation dependency in pom.xml file.
对于那些无法通过 Hibernate 验证依赖项执行服务器端验证的人。
只需删除 Hibernate 验证器 +javax 验证依赖项并添加 spring-boot-starter 验证即可。它内部提供了 Hibernate Validator,它对我来说工作得很好。
致谢:- 来自 youtube 的评论。
For those who have not been able to perform server-side validation through Hibernate validation dependency.
Just remove Hibernate validator +javax validation dependency and add spring-boot-starter validation. It provides Hibernate Validator Internally, and it worked just fine for me.
Credits:- a comment from youtube.
我遇到了同样的问题,但我得到了解决方案,
您的servlet配置xml文件即{servlet-name}-servlet.xml文件
应该像
第4步一样重要
I fell into the same issue, but I got solution
your servlet configuration xml file i.e {servlet-name}-servlet.xml file
should be like
step 4 is important one
就我而言,当切换到 Spring 3 时。注释应该来自 jakarta。例如
反而
导入 javax.validation.constraints.Size;
导入 jakarta.validation.constraints.Size;
In my case when switching to the Spring 3. Annotations should be from jakarta. For example
Instead
import javax.validation.constraints.Size;
import jakarta.validation.constraints.Size;
就我而言,我删除了这些行
1-import javax.validation.constraints.NotNull;
2-导入javax.validation.constraints.Size;
3- @NotNull
4- @Size(最大 = 3)
In my case i removed these lines
1-import javax.validation.constraints.NotNull;
2-import javax.validation.constraints.Size;
3- @NotNull
4- @Size(max = 3)