1、groups
1、給校驗注解,標注上groups,指定什么情況下才需要進行校驗
如:指定在更新和添加的時候,都需要進行校驗。新增時不需要帶id,修改時必須帶id
@NotNull(message = "修改必須定制品牌id", groups = {UpdateGroup.class}) @Null(message = "新增不能指定id", groups = {AddGroup.class}) @TableId private Long brandId;
在這種情況下,沒有指定分組的校驗注解,默認是不起作用的。想要起作用就必須要加groups。
2、@Validated
2、業務方法參數上使用@Validated注解
@Validated的value方法:
Specify one or more validation groups to apply to the validation step kicked off by this annotation.
指定一個或多個驗證組以應用於此注釋啟動的驗證步驟。
JSR-303 defines validation groups as custom annotations which an application declares for the sole purpose of using
them as type-safe group arguments, as implemented in SpringValidatorAdapter.
JSR-303 將驗證組定義為自定義注釋,應用程序聲明的唯一目的是將它們用作類型安全組參數,如 SpringValidatorAdapter 中實現的那樣。
Other SmartValidator implementations may support class arguments in other ways as well.
其他SmartValidator 實現也可以以其他方式支持類參數。
@RequestMapping("/save") public R save(@Validated(AddGroup.class) @RequestBody BrandEntity brand) { brandService.save(brand); return R.ok(); } @RequestMapping("/delete") //@RequiresPermissions("${moduleNamez}:brand:delete") public R delete(@RequestBody Long[] brandIds) { brandService.removeByIds(Arrays.asList(brandIds)); return R.ok(); }
/** * 品牌logo地址 修改可以不帶上logoURL */ @NotBlank(groups = {AddGroup.class}) @URL(message = "logo必須是一個合法的URL地址", groups={AddGroup.class, UpdateGroup.class}) private String logo; 注意上面因為@NotBlank沒有指定UpdateGroup分組,所以不生效。此時update時可以不攜帶,但帶了一定得是url地址
3、分組情況下,校驗注解生效問題
3、默認情況下,在分組校驗情況下,沒有指定指定分組的校驗注解,將不會生效,它只會在不分組的情況下生效。