重写 @NotNull的异常提示
时间: 2023-12-16 14:05:20 浏览: 27
对于重写 @NotNull 注解的异常提示,您可以自定义一个错误消息。可以通过继承 NotNullValidator 类,并重写其中的 validate 方法来实现。
下面是一个示例代码:
```java
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CustomNotNullValidator implements ConstraintValidator<NotNull, Object> {
@Override
public void initialize(NotNull constraintAnnotation) {
// 初始化操作,如果有需要可以在这里进行一些配置
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
context.disableDefaultConstraintViolation(); // 禁用默认的错误提示
context.buildConstraintViolationWithTemplate("自定义的错误消息").addConstraintViolation(); // 设置自定义的错误消息
return false;
}
return true;
}
}
```
在上述代码中,通过调用 `context.disableDefaultConstraintViolation()` 方法来禁用默认的错误提示信息。然后使用 `context.buildConstraintViolationWithTemplate("自定义的错误消息")` 方法来设置自定义的错误消息。
最后,您可以在需要使用 @NotNull 注解的地方,使用这个自定义的验证器来替代默认的验证器。例如:
```java
public class MyClass {
@NotNull(message = "这是自定义的非空错误消息")
private String myField;
// ...
}
```
这样,在校验 myField 字段时,如果字段值为 null,将会使用自定义的错误消息 "这是自定义的非空错误消息"。
希望对您有所帮助!如果还有其他问题,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)