转自:
Spring中@Valid和@Validated有哪些不同呢?
下文笔者讲述Spring中@Valid和@Validated的区别,如下所示:
@Valid和@Validated的区别
@Valid | @Validated | |
标准 | 标准JSR-303规范 | 增强JSR-303规范 |
包 | javax.validation | org.springframework.validation |
验证结果 | BindingResult result | BindingResult result |
分组支持 | 不支持 | 支持 |
分组序列 | 不支持 | 支持 |
类型注解 | ? | 支持 |
方法注解 | 支持 | 支持 |
方法参数注解 | 支持 | 支持 |
构造函数注解 | 支持 | ? |
成员属性注解 | 支持 | 不支持 |
嵌套验证 | 支持 | 不支持 |
例
public interface First{} public interface Second{} public class User { // 所有都验证 @NotNull(message = "...") private int id; // First 才验证 @NotNull(message = "...", groups = { First.class }) private String username; // First 或 Second 才验证 @NotNull(message = "...", groups = { First.class, Second.class }) private String content; // First 验证 NotEmpty,Second 验证 Size @NotEmpty(message = "...", groups = { First.class }) @Size(message = "...", min = 3, max = 8, groups = { Second.class }) private String height; } // 只验证 Second 分组和没有分组的属性 public String save(@Validated( { Second.class }) User user, BindingResult result) { if (result.hasErrors()) { return "validate/error"; } return "redirect:/success"; }
分组序列
public interface GroupA {} public interface GroupB {} @GroupSequence( { GroupA.class, GroupB.class }) public interface Group {} public @ResponseBody String save(@Validated({ Group.class }) User user, BindingResult result) { if(result.hasErrors()) { return false; } return true; }
嵌套验证
public class Item { @NotNull(message = "id不能为空") @Min(value = 1, message = "id必须为正整数") private Long id; @Valid @NotNull(message = "props不能为空") @Size(min = 1, message = "至少要有一个属性") private List<Prop> props; } public class Prop { @NotNull(message = "pid不能为空") @Min(value = 1, message = "pid必须为正整数") private Long pid; @NotNull(message = "vid不能为空") @Min(value = 1, message = "vid必须为正整数") private Long vid; @NotBlank(message = "pidName不能为空") private String pidName; @NotBlank(message = "vidName不能为空") private String vidName; } @RestController public class ItemController { @RequestMapping("/item/add") public void addItem(@Validated Item item, BindingResult bindingResult) { doSomething(); } }
验证多个对象
@Controller public class PeopleController { @RequestMapping("/add") public @ResponseBody String add(@Validated People pp, BindingResult result1, @Validated Person ps, BindingResult result2) { if(result1.hasErrors()) { return false; } if(result2.hasErrors()) { return false; } return true; } }