Java笔记 #07# Hibernate Validator
Hibernate Validator是Spring Boot默认附带的标准校验API(javax.validation)实现。
应用实例(配合切面)
采用注解定义切面.java
@Aspect @Configuration public class ParameterValidator { private ExecutableValidator executableValidator; public ParameterValidator() { // 开启快速失败返回模式(顾名思义...) ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class). configure().addProperty("hibernate.validator.fail_fast", "true" ). buildValidatorFactory(); executableValidator = validatorFactory.getValidator().forExecutables(); } @Pointcut("execution(public * org.sample.website.service.impl.*.*(..))") public void serviceMethod() {} @Around("serviceMethod()") public Object validate(ProceedingJoinPoint jp) throws Throwable { Method method = ((MethodSignature) jp.getSignature()).getMethod(); Set<ConstraintViolation<Object>> violations = executableValidator.validateParameters(jp.getThis(), method, jp.getArgs()); if (!violations.isEmpty()) { throw new ValidationException(violations.iterator().next().getMessage()); } return jp.proceed(); } }
PS. ValidationException是标准API中定义的运行时异常
/
接口.java
public interface MessageService { // 单独校验参数 Message leaveMessage(@NotNull(message = "昵称不能为空") String nickname, @NotNull(message = "内容不能为空") String content); Message leaveMessage(@Valid Message message); // 校验实体 List<Message> listMessage(int offset, int limit); }
/
参数中的实体只有在@Valid(递归校验符)标注后才会被校验:
public class Message { private Long id; private String nickname; @NotNull(message = "内容不能为空!") private String content; public Message() { }
/
测试代码片段(Spring环境):
String nickname = "test" + (int) (Math.random() * 10); messageService.leaveMessage(new Message(nickname, null));
运行结果:
javax.validation.ValidationException: 内容不能为空!
at org.sample.website.aspect.ParameterValidator.validate(ParameterValidator.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)