英文:
java lombok bean validation
问题
我有以下代码,在代码中我将文本字段标记为 @NotNull
,并尝试通过将 null
值传递到该字段来创建对象。
我发现验证并未起作用。程序成功完成,文本的值为 null
。
我想知道我在这里漏掉了什么,为什么在创建对象时没有抛出异常?
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@AllArgsConstructor
@Getter
@Setter
public class testInput {
private int id;
@Valid
@NotNull(message = "text not be null")
private String text;
public static void main(String args[]){
System.out.println("Starting");
testInput inp = new testInput(1,null);
System.out.println("Ending");
}
}
英文:
I have below code, where I marked the text field as @NotNull
, and I tried to create object by passing null
value into that field.
I don't see the validation works. The program completes successfully with the value for text as null
Can I please know what I am missing here and why no exception is thrown while creating the object?
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
@AllArgsConstructor
@Getter
@Setter
public class testInput {
private int id;
@Valid
@NotNull(message = "text not be null")
private String text;
public static void main(String args[]){
System.out.println("Starting");
testInput inp = new testInput(1,null);
System.out.println("Ending");
}
}
答案1
得分: 1
你可以使用 Lombok 的 NonNull
。如果将 null 作为参数传递,它将抛出一个 NullPointerException
,而不会将验证器关联到您的代码。
import lombok.NonNull;
@NonNull
private String text;
英文:
You can use Lombok's NonNull
. If a null is passed as an argument, it will throw a NullPointerException
, without associating a validator to your code.
import lombok.NonNull;
@NonNull
private String text;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论