1. 程式人生 > 程式設計 >spring @Validated 註解開發中使用group分組校驗的實現

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

之前知道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分組校驗內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!