Java中@valid和@Validated注解的使用詳解
1.簡介
- @Validated:可以用在類型、方法和方法參數(shù)上。但是不能用在成員屬性(字段)上,不支持嵌套檢測
- @Valid:可以用在方法、構(gòu)造函數(shù)、方法參數(shù)和成員屬性(字段)上,支持嵌套檢測
2.引入maven
springboot 2.3.0 以后不會自動引入jar包,所以要添加以下maven,2.3以前則不需要引入maven包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
3.配合使用注解
- @Null 限制只能為null
- @NotNull 限制必須不為null
- @AssertFalse 限制必須為false
- @AssertTrue 限制必須為true
- @DecimalMax(value) 限制必須為一個不大于指定值的數(shù)字
- @DecimalMin(value) 限制必須為一個不小于指定值的數(shù)字
- @Digits(integer,fraction) 限制必須為一個小數(shù),且整數(shù)部分的位數(shù)不能超過integer,小數(shù)部分的位數(shù)不能超過fraction
- @Future 限制必須是一個將來的日期
- @Max(value) 限制必須為一個不大于指定值的數(shù)字
- @Min(value) 限制必須為一個不小于指定值的數(shù)字
- @Past 限制必須是一個過去的日期
- @Pattern(value) 限制必須符合指定的正則表達式
- @Size(max,min) 限制字符長度必須在min到max之間
- @Past 驗證注解的元素值(日期類型)比當前時間早
- @NotEmpty 驗證注解的元素值不為null且不為空(字符串長度不為0、集合大小不為0)
- @NotBlank 驗證注解的元素值不為空(不為null、去除首位空格后長度為0),不同于@NotEmpty,@NotBlank只應用于字符串且在比較時會去除字符串的空格
- @Email 驗證注解的元素值是Email,也可以通過正則表達式和flag指定自定義的email格式
4.例子
4.1 model
@Valid 定義schoole屬性是為了實現(xiàn)嵌套驗證,沒有這個注解無法校驗school類內(nèi)部需要校驗的屬性。
public class UserVO { @NotNull(message = "id不能為空。" ,groups = {Insert.class}) private Integer id; @NotBlank(message = "name不能為空。",groups = {Update.class}) private String name; @NotNull(message = "schoole不能為空。") @Valid private Schoole schoole; @Min(value = 1,message = "age不能小于1") @Max(value = 130,message = "age不能大于130") private int age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Schoole getSchoole() { return schoole; } public void setSchoole(Schoole schoole) { this.schoole = schoole; }
public class Schoole { @NotBlank(message = "name不能為空。",groups = {Update.class}) private String name; @NotNull(message = "id不能為空") private Integer id; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; }
4.2分組接口
實現(xiàn)Default 接口,不然@Validated({Update.class}) 使用Update分組時,未定義分組的默認校驗屬性不會生效(比如校驗schoole的 @NotNull(message = “schoole不能為空。”))
import javax.validation.groups.Default; public interface Insert extends Default { } public interface Update extends Default { }
4.3controller
@Validated 標明group 時(Update.class)只有需要校驗屬性上校驗注解含有該接口(Update.class)才生效,如果group (Update.class)實現(xiàn)了Default接口那么需要校驗屬性上的校驗注解未定義任何group 時也會生效。
@RestController @RequestMapping("/valid") public class TestValidController { private static final Logger LOG = LoggerFactory.getLogger(TestValidController.class); @RequestMapping("/test") public void testValid(@Validated({Update.class}) UserVO userVO){ LOG.info("userVo:"+userVO); } @PostMapping("/test2") public void testValid2(@Validated() @RequestBody UserVO userVO){ LOG.info("userVo:"+userVO); } }
4.3.1 基本數(shù)據(jù)類型校驗
需要在類上加@Validated,然后方法直接使用@NotNull等校驗注解
@Validated public class HrmEmployeeContractController { @Resource private IHrmEmployeeContractService contractService; @GetMapping("/listByEmployeeId2") public ResponseUtil listByEmployeeId2( @NotNull(message = "employeeId 不能為空") Long employeeId) { return ResponseUtil.success(contractService.list(Wrappers.<HrmEmployeeContract>lambdaQuery() .eq(HrmEmployeeContract::getEmployeeId, employeeId) .eq(HrmEmployeeContract::getDeleted, DataStatusEnum.ENABLE.getType()))); } }
4.4使用全局異常攔截器攔截參數(shù)校驗異常
MethodArgumentNotValidException異常由@RequestBody 修飾的參數(shù)未校驗過拋出,其他未校驗通過拋出異常BindException。
@RestControllerAdvice public class GlobalExceptionHandler { private Logger LOG= LoggerFactory.getLogger(GlobalExceptionHandler.class); //BindException 校驗參數(shù)不滿足條件拋出 @ExceptionHandler(BindException.class) public Object handleValidException(BindException e) { return ResponseUtil.fail(400,e.getBindingResult().getFieldError().getDefaultMessage()); } //MethodArgumentNotValidException @RequestBody 修飾的參數(shù)未校驗過拋出 @ExceptionHandler(MethodArgumentNotValidException.class) public Object handleValidException2(MethodArgumentNotValidException e) { return ResponseUtil.fail(400,e.getBindingResult().getFieldError().getDefaultMessage()); } @ExceptionHandler(RuntimeException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public ResponseUtil handleRuntimeException(RuntimeException ex) { int code = 500; String message = ex.getMessage(); LOG.error(ex.getMessage(), ex); return ResponseUtil.fail(code,message); } @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public ResponseUtil handleException(Exception ex) { int code = 500; String message = ex.getMessage(); LOG.error(ex.getMessage(), ex); return ResponseUtil.fail(code,message); } }
測試
結(jié)果:
Schoole 里面的id 每天報id不能為空
spring Validation 默認會校驗完所有字段,然后拋異常,可以配置快速失敗,一旦校驗失敗立馬拋異常。
@Bean public Validator validator(){ ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure() .failFast(true) .buildValidatorFactory(); return validatorFactory.getValidator(); }
到此這篇關于Java中@valid和@Validated注解的使用詳解的文章就介紹到這了,更多相關@valid和@Validated注解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
14個編寫Spring MVC控制器的實用小技巧(吐血整理)
這篇文章主要介紹了14個編寫Spring MVC控制器的實用小技巧(吐血整理),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11SparkSQL使用IDEA快速入門DataFrame與DataSet的完美教程
本文給大家介紹使用idea開發(fā)Spark SQL 的詳細過程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2021-08-08