我把注解@valid放在servevice层上是没有效果的,只有放在Controller上才有效果??
1 回答
蓝山帝景
TA贡献1843条经验 获得超7个赞
可以手动校验,代码如下。
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.util.Set;
class Test{
private static class User {
@NotNull(message = "姓名不能为空")
private String name;
@Min(value = 1 ,message = "年龄不能小于0")
@NotNull(message = "age不能为空")
private Integer age;
@NotNull(message = "id不能为空")
private Integer id;
//省略get set方法
}
//验证代码
public static void main(String[] args) {
User user = new User();
validate(user);
}
private static void validate(Object o){
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();
Set<ConstraintViolation<Object>> set = validator.validate(o);
for (ConstraintViolation<Object> constraintViolation : set) {
System.out.println(constraintViolation.getPropertyPath()+":"+constraintViolation.getMessage());
}
}
}
添加回答
举报
0/150
提交
取消