spring项目非controller方法上使用@Valid / service类方法使用@Valid校验参数
top:参考博客:
https://blog.csdn.net/f641385712/article/details/97402946
1. 方法校验bean添加到spring容器:
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import javax.validation.Validation;
import javax.validation.Validator;
@Configuration
public class ValidConfigBean {
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
postProcessor.setBeforeExistingAdvisors(true);
postProcessor.setProxyTargetClass(true);
postProcessor.setValidator(validator());
return postProcessor;
}
/**
* 开启快速失败模式,一旦失败立即抛出异常
*
* @return
*/
@Bean
public Validator validator() {
return Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
}
}
2. 校验配置
2.1 自定义校验组:
public interface GroupInsert {
}
2.2 自定义model:
@Data
public class ValidDto {
@NotNull(groups = GroupInsert.class)
private Integer validInteger;
@NotBlank
private String validString;
}
2.3 接口校验规则定义:@NotBlank,@Valid…
public interface ValidService {
/**
* 校验参数
* @param id
* @return
*/
String normal(@NotBlank String id);
/**
* 校验model
* 默认:@Validated(Default.class)
* @param validDto
* @return
*/
String normalObject(@Valid ValidDto validDto);
/**
* 校验model-指定组
* normalObject 默认:@Validated(Default.class)
* @param validDto
* @return
*/
@Validated(GroupInsert.class)
String groupObject(@Valid ValidDto validDto);
}
2.4 实现类声明支持校验参数:@Validated
@Service
@Validated
public class ValidServiceImpl interface ValidService{
// 实现方法...
}
2.5 controller示例:
@RestController
@RequestMapping
public class TestValidController {
@Resource
private ValidService validService;
@GetMapping("/normal")
public String normal(@RequestParam("id") String id) {
return validService.normal(id);
}
@GetMapping("/normalObject")
public String normalObject(@ModelAttribute ValidDto validDto) {
return validService.normalObject(validDto);
}
@GetMapping("/groupObject")
public String groupObject(@ModelAttribute ValidDto validDto) {
return validService.groupObject(validDto);
}
}