Sure, here’s the translation: java lombok bean validation

huangapple go评论95阅读模式
英文:

java lombok bean validation

问题

我有以下代码,在代码中我将文本字段标记为 @NotNull,并尝试通过将 null 值传递到该字段来创建对象。

我发现验证并未起作用。程序成功完成,文本的值为 null

我想知道我在这里漏掉了什么,为什么在创建对象时没有抛出异常?

  1. import lombok.AllArgsConstructor;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. import javax.validation.Valid;
  5. import javax.validation.constraints.NotNull;
  6. @AllArgsConstructor
  7. @Getter
  8. @Setter
  9. public class testInput {
  10. private int id;
  11. @Valid
  12. @NotNull(message = "text not be null")
  13. private String text;
  14. public static void main(String args[]){
  15. System.out.println("Starting");
  16. testInput inp = new testInput(1,null);
  17. System.out.println("Ending");
  18. }
  19. }
英文:

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?

  1. import lombok.AllArgsConstructor;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. import javax.validation.Valid;
  5. import javax.validation.constraints.NotNull;
  6. @AllArgsConstructor
  7. @Getter
  8. @Setter
  9. public class testInput {
  10. private int id;
  11. @Valid
  12. @NotNull(message = "text not be null")
  13. private String text;
  14. public static void main(String args[]){
  15. System.out.println("Starting");
  16. testInput inp = new testInput(1,null);
  17. System.out.println("Ending");
  18. }
  19. }

答案1

得分: 1

你可以使用 Lombok 的 NonNull。如果将 null 作为参数传递,它将抛出一个 NullPointerException,而不会将验证器关联到您的代码。

  1. import lombok.NonNull;
  2. @NonNull
  3. 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.

  1. import lombok.NonNull;
  2. @NonNull
  3. private String text;

huangapple
  • 本文由 发表于 2020年9月27日 18:34:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64087464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定