@Validated注解在service层无效,dto字段上加了@NotBlank等注解,在controller层是可以的
实现类
@Service
@Validated
public class ServiceImpl implements Service, Handler
public Long addInfo(@Valid Dto dto){
// ValidationUtils.validateEntity(dto, AddGroup.class);暂时在方法里写了校验
return null;
}
}
接口
@Validated
public interface Service {
Long addInfo(@Valid Dto dto);
}
@Configuration
public class ValidationConfig {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
}
引入
spring-boot-starter-validation
依赖(Spring Boot 2.x 默认支持javax.validation
):在 Service 层正确使用
@Validated
:DTO使用
javax.validation.constraints
提供的注解:注册
MethodValidationPostProcessor
以支持@Validated
:补充
@Validated
是 Spring 的注解,可用于类或方法参数,支持分组验证@Valid
是 JSR-303 规范的注解,主要用于对象属性级联验证@Validated
,在需要验证的方法参数上使用@Valid
需要同时引入
spring-boot-starter-validation
依赖来确定这些验证功能正常