在Spring Boot中,如何使@Validated注解在Service层生效?

spring boot中,要使@validated注解在service层生效,可以采取以下步骤:

首先,我们需要在spring boot应用程序的主启动类中添加@EnableMethodValidation注解,以启用方法级别的验证功能:

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

接下来,我们将通过一个完整的示例展示如何在Service层使用@Validated注解进行参数验证。

首先,定义一个验证组:

public interface AddGroup {}

然后,定义DTO类,并在字段上添加验证注解,如@NotBlank:

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层中,使用@Validated注解确保参数校验生效:

@Service @Validated // 确保类支持参数校验 public class ServiceImpl implements Service {      public Long addInfo(@Validated(AddGroup.class) Dto dto) {         // 校验通过后执行业务逻辑         System.out.println("Name: " + dto.getName());         return 1L;     } }

最后,在Controller层进行测试:

@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";     } }

通过以上步骤,可以确保在Service层中使用@Validated注解进行参数校验时,校验功能能够正常生效。

在Spring Boot中,如何使@Validated注解在Service层生效?

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享