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

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

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;

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:

确定