利用JSR-303做验证怎么验证service层?

我把注解@valid放在servevice层上是没有效果的,只有放在Controller上才有效果??

呼啦一阵风
浏览 584回答 1
1回答

蓝山帝景

可以手动校验,代码如下。 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()); } } }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java