项目backend模块Controller层和api模块service层使用注解校验
1、校验单参数
- 在对应类上加@Validated注解
- 在接口参数上添加校验注解
注意是在类上添加@Validated
@RestController
@Validated
public class ResourceController extends BaseController {
@GetMapping("/resourceCenter/paper/analyseByDifficulty")
public List<DifficultyAnalyseInfo> analyseByDifficulty(@NotNull(message = "paperId不能为空") Long paperId) {
return resourceCenterService.analyseByDifficulty(paperId);
}
}
@FeignClient(name = "cloud-aital-resource-svc", decode404 = true, url = "${feign.url.cloud-aital-resource-svc:}")
@Validated
public interface ResourceService {
@GetMapping("/resource/file")
ApiResult<EcpFileDTO> getResourceFile(@NotNull(message = "fileId不能为空") Long fileId);
}
2、对引用类型(封装参数对象)参数校验
- 在对象参数需要校验的属性上添加校验注解
- 在接口参数上添加@Valid注解
public class HtmlDownloadRequest implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 下载html代码
*/
@NotBlank(message = "html不能为空!")
private String html;
/**
* 下载文件类型,pdf,docx
*/
@NotBlank(message = "fileType不能为空!")
private String fileType;
/**
* 业务id
*/
@NotNull(message = "业务id不能为空!")
private Long id;
/**
* 对象或集合属性级联校验需要加@Valid注解
*/
@Valid
private EcpFileDTO files;
}
@PostMapping("/resourceCenter/downloadQuestionOrPaper")
public EcpFileDTO downloadQuestionOrPaper(@RequestBody @Valid HtmlDownloadRequest request) {
return resourceCenterService.getHtmlDownloadUrl(request);
}
常见的注解校验