简体   繁体   English

在springboot中发送响应时,我们是否有任何注释来验证响应属性/字段不是null?

[英]Do we have any annotations to validate the response attribute/fields are not null while sending the response in springboot?

Below is the 'Student' response class with getter and setter, I am setting the values with the help of setter, with the help of null checks in codes, it can be done but do we have any annotations for that?下面是带有 getter 和 setter 的“学生”响应 class,我在 setter 的帮助下设置值,在 null 检查代码的帮助下,它可以完成,但我们有任何注释吗?

 Class Student
    {
     String name;
     String rollno;
     String collegeName;
    
     //Getter and setter
   }

There are two ways to perform validation: Implement your own utility class for validation of objects and validate objects prior passing to some method or use @Valid annotation on your objects you are going pass to the method:有两种执行验证的方法:实现您自己的实用程序 class 以验证对象并在传递给某个方法之前验证对象,或者在您要传递给该方法的对象上使用@Valid注释:

public void saveStudent(@Valid Student student);

In your Student class required String fields must be annotated with @NotBlank or NotNull for other types.在您的Student class 中,必须使用@NotBlankNotNull对其他类型的必需字符串字段进行注释。

Don't forget to add required dependencies for validation such as:不要忘记添加验证所需的依赖项,例如:

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator-annotation-processor</artifactId>
    <version>6.0.2.Final</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

This is what you can do with your response class:这是您可以对您的响应 class 执行的操作:

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseClass implements Serializable {

}

This is will not include null and unknown fields in your response json.这将不包括 null 和您的响应 json 中的未知字段。

You can try to use @NonNull annotation from Lombok ( link )您可以尝试使用 Lombok 中的@NonNull注释(链接

Assume your class is:假设您的 class 是:

@Getter
@Setter
@AllArgsConstructor
public class Student {

    @NonNull private String name;
    @NonNull private String rollno;
    @NonNull private String collegeName;
}

And here is the test:这是测试:

@Test
void CreateStudent() {
    Assertions.assertThrows(NullPointerException.class, () -> new Student("John", "42", null));
}

update更新

In your case (no custom constructors, only default), yo should add @NonNull annotation to your setter:在您的情况下(没有自定义构造函数,只有默认值),您应该将@NonNull注释添加到您的设置器中:

public void setName(@NonNull String name) {
    this.name = name;
}

And here is the test:这是测试:

@Test
void CreateStudent() {
    Student student = new Student();
    Assertions.assertThrows(NullPointerException.class, () -> student.setName(null));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM