Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

java - Working of javax.validation @NotBland and lombok @NonNull

I have a simple User class and its properties are annotated with both @NotBland and lombok @NonNull.

@AllArgsConstructor
@Data
@Builder
public class User {

    @NonNull
    private String name;

    @NonNull
    private String id;

    @NotBlank
    private String address;
}

What i am expecting from this is when i try to set blank in address field it informs me at compile time or at least crash at runtime. Lombok @NonNull is working in that way and is raising NPEs at runtime.

I wrote the following test to check this

@Test
public void user_null_test(){

    User user = User.builder()
            .id("")
            .name("")
            .address("")
            .build();



    assertThat(user).isNotNull();

But the user is a valid user object with address being empty. Obviously i can use the following code to check for validation in my test

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertThat(violations).isEmpty(); 

but i can't do that or want to write this type of code in my actual code base. So my question is what is the use of @NotBlank if it does not raise any error at compile or run time if we are setting a property to as empty string when it is not supposed to be so according to the set annotation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.7k users

...