约束验证@Null的意义是什么? [英] What is point of constraint validation @Null?

查看:142
本文介绍了约束验证@Null的意义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查可用约束列表javax.validation包中,我注意到有一个注释

I was checking list of available constraints in javax.validation package and I noticed that there is an annotation @Null which force the field to be null.

如果我已经知道应该将其添加为空,那么我不知道将其添加到字段中的意义.

I do not understand what is point of adding it to my field if I already know it should be null.

例如,查看此类:

public class MyClass{

    @NotNull
    private String myString1;

    @Null
    private String myString2;

    // getter setters...
}

@NotNull完全有意义.我不希望myString1为空.但是@Null使myString2无效.具有始终为空的字段的意义是什么.

@NotNull completely makes sense. I do not expect myString1 to be null. but @Null makes myString2 useless. What is point of having a field which should always be null.

推荐答案

仅在某些情况下,您可能需要结合使用@Null和验证组"来验证null约束.

You may want to use @Null in combination with "Validation Group" to validate the null constraint only in certain cases.

很好的解释和Hibernate提供的验证组示例

您将定义验证组为简单界面

You will define validation group as simple interface

public interface FirstSave {}

然后在约束条件下使用它

then use it in constraint

public class MyClass {

    @Null(groups = FirstSave.class)
    private LocalDate lastUpdate;
}

然后,如果lastUpdate 不是 null,则调用validator.validate(myClassInstance) 不会会产生约束冲突(使用默认组),但是调用validator.validate(myClassInstance, FirstSave.class)

then if lastUpdate is not null, calling validator.validate(myClassInstance) will not produce constraint violation (Default group was used), but calling validator.validate(myClassInstance, FirstSave.class) will.

您还可以提供有关如何使用注释的自己的实现,即,我已经看到验证方法以@Null进行注释,其中方法返回的null表示一切正常.在后台,如果带注释的方法返回的结果不是null,该怎么做可能是自定义实现,但是我没有深入研究代码...

You also have the possibility to provide your own implementation on how to use the annotation, i.e. I've seen validation method being annotated with @Null where null returned by the method meant that everything is alright. In the background there was probably custom implementation on what to do if annotated method returned not null result, but I didn't go deep into the code...

这篇关于约束验证@Null的意义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆