为什么@Validated注解controller层有效,在service层无效?

@Validated注解在service层无效,dto字段上加了@NotBlank等注解,在controller层是可以的

@Service
public class ServiceImpl implements Service
  public Long addInfo(@Validated(AddGroup.class) Dto dto){
  }
}
阅读 428
1 个回答

如果是SpringBoot3+中,在启动类中添加 @EnableMethodValidation 注解:

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

测试示例

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";
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题