×ðÁú¿­Ê±

@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×¢½â²ÎÊý¼°Ê¹Óý̵̳ÄÏêϸÄÚÈÝ £¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí £¬°æȨÕùÒéÓë±¾Õ¾ÎÞ¹Ø £¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±ÂËÓÍ»úÍø¹Ù·½Ì¬¶È £¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ £¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢ £¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢ £¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±ÊµÊ±ÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎå £¬9:30-18:30 £¬½ÚãåÈÕÐÝÏ¢

QR code
¡¾ÍøÕ¾µØͼ¡¿¡¾sitemap¡¿