spring 注解 - @NotNull - 确保字段或参数值不为 null
@NotNull 是 Bean Validation API(JSR 303/JSR 349)中的一个注解,用于确保一个字段或参数值不为 null
。这个注解可以用于 Java 类的字段、方法的参数或者方法的返回值上,以确保在运行时这些值不为空。
使用场景
字段验证:当你定义一个实体类或 DTO(Data Transfer Object)时,你可以使用 @NotNull
来确保某个字段在业务逻辑中必须有值。
public class User {@NotNull(message = "Username cannot be null")private String username;// getters and setters
}
方法参数验证:在服务层或控制器层的方法中,你可以使用 @NotNull
来确保传入的参数不为 null
。
public void registerUser(@NotNull(message = "User object cannot be null") User user) {// 注册用户逻辑
}
@NotNull 是一个强大的验证工具,可以帮助你确保应用程序中的数据完整性和一致性。通过合理使用这个注解,你可以减少运行时错误并提高代码的可维护性。