@validated×¢½â²ÎÊý¼°Ê¹Óý̳Ì
@validated ×¢½âÓÃÓÚÑéÖ¤ÒªÁì²ÎÊýºÍÇëÇóÌ壬Æä²ÎÊý°üÀ¨£ºvalue£ºÖ¸¶¨Ð£ÑéÆ÷Ààgroups£ºÖ¸¶¨Ð£Ñé×飬ÔÊÐíƾ֤³¡¾°×Ô½ç˵¹æÔò
@validated ×¢½â²ÎÊý¼°Ê¹Óý̳Ì
¼ò½é
@Validated ×¢½âÊÇ Spring Boot ÓÃÓÚÑéÖ¤ÒªÁì²ÎÊýºÍÇëÇóÌåµÄÓÐÓÃÐÔµÄ×¢½â¡£Ëü¿ÉÒÔÓë²î±ðµÄУÑéÆ÷Ò»ÆðʹÓ㬰üÀ¨ JSR-303¡¢Bean Validation ºÍ Hibernate Validator¡£
²ÎÊý
@Validated ×¢½âµÄ²ÎÊýÈçÏ£º
- value: Ö¸¶¨ÒªÊ¹ÓõÄУÑéÆ÷Àà¡£ÈôÊÇδָ¶¨£¬½«Ê¹ÓÃĬÈÏУÑéÆ÷£¨Í¨³£ÊÇ Hibernate Validator£©¡£
- groups: Ö¸¶¨ÒªÓ¦ÓõÄУÑé×顣УÑé×éÔÊÐíƾ֤²î±ðµÄ³¡¾°×Ô½ç˵ÑéÖ¤¹æÔò¡£
ʹÓÃ
ҪʹÓà @Validated ×¢½â£¬ÐèÒª½«Æä·ÅÔÚÐèÒªÑéÖ¤µÄÒªÁì²ÎÊý»òÇëÇóÌå֮ǰ¡£ÀýÈ磺
@PostMapping("/user") public User createUser(@RequestBody @Validated User user) { // ´úÂëÂÔ }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬@Validated ×¢½âÅú×¢ user ²ÎÊýÓ¦¸ÃʹÓÃĬÈÏУÑéÆ÷¾ÙÐÐÑéÖ¤¡£ÈôÊÇÓû§ÇëÇóÌåÖÐȱÉÙ±ØÌî×ֶλò×Ö¶ÎÃûÌò»×¼È·£¬Spring Boot ½«Å׳öÒ»¸ö MethodArgumentNotValidException Òì³£¡£
УÑé×é
УÑé×éÔÊÐíƾ֤²î±ðµÄ³¡¾°×Ô½ç˵ÑéÖ¤¹æÔò¡£Òª½ç˵УÑé×飬¿ÉÒÔʹÓà @ValidationGroups ×¢½â¡£ÀýÈ磺
public interface UserValidationGroups { interface Create {} interface Update {} }
µÇ¼ºó¸´ÖÆ
È»ºó£¬¿ÉÒÔÔÚʹÓà @Validated ×¢½âʱָ¶¨Ð£Ñé×飺
@PostMapping("/user") public User createUser(@RequestBody @Validated(groups = UserValidationGroups.Create.class) User user) { // ´úÂëÂÔ }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄʾÀýÖУ¬@Validated ×¢½âÖ¸¶¨ÁË UserValidationGroups.Create УÑé×é¡£ÕâÒâζ×ÅÔÚ½¨ÉèÓû§Ê±½«Ó¦ÓøÃ×éÖеÄÑéÖ¤¹æÔò¡£
ÒÔÉϾÍÊÇ@validated×¢½â²ÎÊý¼°Ê¹Óý̵̳ÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡