@Validated注解在Spring Boot項目中為何在service層無效,而在controller層有效?

spring boot項目中,@validated注解在不同層級的使用可能存在差異。讓我們通過一個具體的案例來探討為什么@validated注解在controller層有效,而在service層無效,以及如何解決這個問題。

spring boot項目中@Validated注解在不同層級的使用問題

在Spring Boot項目開發中,我們經常使用@Validated注解來進行參數校驗。然而,有時會發現這個注解在controller層有效,但在service層卻無法正常工作。讓我們深入探討這個問題并找到解決方案。

問題描述

當我們在service層使用@Validated注解,并在DTO類的字段上添加了@NotBlank等注解時,校驗在controller層可以正常工作,但在service層卻無法生效。

示例代碼如下:

@Service public class ServiceImpl implements Service {     public Long addInfo(@Validated(AddGroup.class) Dto dto) {         // ...     } }

問題解析及解決方案

在Spring Boot 3及以上版本中,默認情況下,@Validated注解在service層不會自動生效。要使其在service層也生效,需要在啟動類中添加@EnableMethodValidation注解。

具體操作如下:

@SpringBootApplication @EnableMethodValidation public class Application {     public static void main(String[] args) {         SpringApplication.run(Application.class, args);     } }

此外,為了確保服務層的方法能夠正確使用@Validated注解進行參數校驗,還需要在服務類上添加@Validated注解:

import jakarta.validation.constraints.NotBlank; import jakarta.validation.groups.Default; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated;  // 定義校驗組 public interface AddGroup {}  // 定義 DTO 類 public class Dto {      @NotBlank(groups = {AddGroup.class, Default.class}) // 多個驗證組     private String name;      // Getter 和 Setter     public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     } }  // Service 層 @Service @Validated // 確保類支持參數校驗 public class ServiceImpl {      public Long addInfo(@Validated(AddGroup.class) Dto dto) {         // 校驗通過后執行業務邏輯         System.out.println("Name: " + dto.getName());         return 1L;     } }  // Controller 層(測試 Service 調用) @RestController @RequestMapping("/test") public class TestController {      private final ServiceImpl service;      public TestController(ServiceImpl service) {         this.service = service;     }      @PostMapping("/add")     public String addInfo(@RequestBody Dto dto) {         service.addInfo(dto);         return "Success";     } }

通過以上配置和代碼示例,可以確保@Validated注解在service層也能正常工作,從而實現參數校驗功能。

@Validated注解在Spring Boot項目中為何在service層無效,而在controller層有效?

? 版權聲明
THE END
喜歡就支持一下吧
點贊15 分享