您的位置:首頁技術文章
文章詳情頁

spring @Validated 注解開發中使用group分組校驗的實現

瀏覽:91日期:2023-09-06 08:47:49

之前知道spring支持JSR校驗,在自己定義的bean中加入@NotNull,@NotBlank,@Length等之類的校驗用于處理前臺傳遞過來的request請求,避免在寫多余的代碼去處理.

但是隨著業務的復雜度增加,對于校驗的制定也越來越有要求,這個時候就需要引入分組group的概念,在自定義注解@Validated中

spring @Validated 注解開發中使用group分組校驗的實現

定義了一個Class[]數組用來分組.這樣我們就可以引入分組校驗的概念,首先根據需要的分組新建自己的接口.

spring @Validated 注解開發中使用group分組校驗的實現

spring @Validated 注解開發中使用group分組校驗的實現

然后在需要校驗的bean上加入分組:

spring @Validated 注解開發中使用group分組校驗的實現

最后根據需要,在Controller處理請求中加入@Validated注解并引入需要校驗的分組.

@Validated({Insert.class})AgentContractBean paramBean

整個Spring請求bean的分組校驗就算是完成了.

使用Spring @Validated 進行Groups驗證是遇到的坑

最近新項目是使用Hibernate Validator做表單驗證,遇到有id在更新時不能為空,而在添加時需要為空的情況,所有使用了group屬性來指定在什么情況下使用哪個驗證規則,而在Controller方法只使用@Validated({Creation.class})來分組驗證:

public ApiResponse<UserDTO> createUser(@Validated({Creation.class}) @RequestBody UserDTO userDTO) { log.debug('創建用戶 : {}', userDTO); if (userRepository.findOneByLoginName(userDTO.getLoginName().toLowerCase()).isPresent()) { return ApiResponse.ofFailure('用戶名已存在'); } else { UserDTO newUser = userService.createUser(userDTO); return ApiResponse.ofSuccess(newUser); } }

但是出現其他字段不執行驗證的問題,找了一大圈,發現@Validated在分組驗證時并沒有添加Default.class的分組,而其他字段默認都是Default分組,所以需要讓分組接口繼承Default:

public interface Creation extends Default {}

到此這篇關于spring @Validated 注解開發中使用group分組校驗的實現的文章就介紹到這了,更多相關spring @Validated group分組校驗內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
国产综合久久一区二区三区