1. 关于 @Validated 与Valid使用
一般加在类上,也可以加在方法上,或者方法里面,
如下面案列
@RestController
@RequestMapping("/receive")
@Validated
public class ReceiveController {
/**
* 分页查询
*
* @param request 查询参数
* @return 收款列表
*/
@GetMapping("/page")
public PageInfo<PageReceiveVO> listByPage(@Valid ReceivePageRequest request) {
request.setOperatorEnterpriseId(HeaderHelper.getEnterpriseId());
request.setTenantId(HeaderHelper.getTenantId());
return receiveService.listByPage(request);
}
/**
* 新增
*
* @param receiveDTO 入参
*/
@PostMapping("/save")
public void save(@RequestBody @Valid ReceiveDTO receiveDTO) {
receiveDTO.setTenantId(HeaderHelper.getTenantId());
receiveDTO.setOperator(HeaderHelper.getCustomerId());
receiveDTO.setOperatorName(HeaderHelper.getUserName());
receiveDTO.setPayeeId(HeaderHelper.getCustomerId());
receiveDTO.setPayeeName(HeaderHelper.getUserName());
receiveDTO.setOperatorEnterpriseId(HeaderHelper.getEnterpriseId());
if (receiveDTO.getId() == null) {
receiveService.saveReceive(receiveDTO);
} else {
receiveService.updateReceive(receiveDTO);
}
}
/**
* 根据收款Id查询详情
*
* @param id 收款Id
* @return ReceiveDetailVO 收款详情
*/
@GetMapping("/detail")
public ReceiveDetailVO detail(@NotNull(message = "收款Id不能为空") Long id) {
return receiveService.detail(id);
}
/**
* 认领操作
*
* @param claims 认领
*/
@PostMapping("/claim")
public void claim(@RequestBody @Valid @Size(min = 1, message = "认领记录最少需要一条") List<ClaimDTO> claims) {
BaseParameter request = new BaseParameter();
request.setTenantId(HeaderHelper.getTenantId());
request.setOperator(HeaderHelper.getCustomerId());
request.setOperatorName(HeaderHelper.getUserName());
request.setOperatorEnterpriseId(HeaderHelper.getEnterpriseId());
receiveService.claim(claims, request);
}
如上面的案列所示:
-
Controller类上加@Validated 表示对该整个类进行校验
-
入参不是对象,则直接使用校验注解即可,切记不要将@RequestParam与校验注解一起使用,会默认走@RequestParam注解,校验注解会失效
下面这种,就是会导致校验注解失效 -
入参是对象,且对象里面的属性也需要校验,以下两种都行
-
入参是集合,只能使用@Valid,而不能使用Validated
-
对象里面还有集合,需要加 @Valid注解