在spring boot中,要使@validated注解在service层生效,可以采取以下步骤:
首先,我们需要在Spring Boot应用程序的主启动类中添加@EnableMethodValidation注解,以启用方法级别的验证功能:
<code>@SpringBootApplication
@EnableMethodValidation
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}</code>接下来,我们将通过一个完整的示例展示如何在Service层使用@Validated注解进行参数验证。
首先,定义一个验证组:
<code>public interface AddGroup {}</code>然后,定义DTO类,并在字段上添加验证注解,如@NotBlank:
<code>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;
}
}</code>在Service层中,使用@Validated注解确保参数校验生效:
<code>@Service
@Validated // 确保类支持参数校验
public class ServiceImpl implements Service {
public Long addInfo(@Validated(AddGroup.class) Dto dto) {
// 校验通过后执行业务逻辑
System.out.println("Name: " + dto.getName());
return 1L;
}
}</code>最后,在Controller层进行测试:
<code>@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";
}
}</code>通过以上步骤,可以确保在Service层中使用@Validated注解进行参数校验时,校验功能能够正常生效。

以上就是在Spring Boot中,如何使@Validated注解在Service层生效?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号