Spring Boot 参数校验

85 阅读1分钟

依赖

Spring Boot 2.3 从 web-starter 移除校验依赖,需要手动添加

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

实体类

@Data  
public class StudentDTO {  
    @NotNull  
    private Long id;  

    @NotNull  
    @NotBlank  
    private String name;  
}

Controller

在 Controller 方法参数上添加 @Validated 注解或 @Valid 注解

如果类路径存在 Bean Validation,LocalValidatorFactoryBean 会作为一个全局的 Validator,用来处理 @Valid@Validted

Service

在类上添加 @Validated 注解,在方法参数添加 @Valid 注解

@Slf4j  
@Service  
@Validated  
public class StudentService {  
    public void addStudent(@Valid StudentDTO studentDTO) {  
        log.info("addStudent:{}", studentDTO);  
    }  
}

测试类

@SpringBootTest  
class StudentServiceTest {  

    @Autowired  
    private StudentService studentService;  

    @Test  
    void addStudent() {  
        StudentDTO studentDTO = new StudentDTO();  
        studentService.addStudent(studentDTO);  
    }  
}

image.png

注解

  • @Valid: Jakarta 注解
  • @Validated:Spring 注解,@Valid 变种,支持校验组