×ðÁú¿­Ê±¹ÙÍøµÇ¼

@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
ÍøÕ¾µØͼ