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)
参考资料
- 在系统中使用Bean Validation验证参数
- springboot使用hibernate validator校验
- Hibernate Validator 校验方法的参数,返回值,构造函数
- http://hibernate.org/validator/documentation/
Java笔记 #07# Hibernate Validator的更多相关文章
- java后台校验 hibernate validator
链接 : https://www.cnblogs.com/softidea/p/6044123.html
- hibernate Validator 6.X 的学习,bean的约束(字段,get方法上的验证)
一:背景说明 验证数据是一个常见的任务,它贯穿于所有应用层,从呈现到持久层.通常在每个层中都执行相同的验证逻辑,耗时且容易出错.为了避免这些验证的重复,开发商往往把验证逻辑直接进入的领域模型,在领域类 ...
- org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.Integer
使用hibernate时,在save方法时,报了:org.hibernate.validator.constraints.NotBlank' validating type 'java.lang.In ...
- JAVA自学笔记07
JAVA自学笔记07 1.构造方法 1) 例如:Student s = new Student();//构造方法 System.out.println(s);// Student@e5bbd6 2)功 ...
- hibernate 解决 java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.internal.engine.xxx 这类的问题
<!-- 解决 java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.intern ...
- hibernate.validator.constraints.NotEmpty校验请求参数报错java.lang.NoClassDefFoundError: javax/el/PropertyNotFoundException
spring maven项目,使用hibernate validator 注解形式校验客户端的请求参数. hibernate-validator版本:5.0.2.Final validation-ap ...
- Caused by: java.lang.AbstractMethodError: org.hibernate.validator.internal.engine.ConfigurationImpl
1.错误描述 严重: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error ...
- java.lang.NoClassDefFoundError: org/hibernate/validator/internal/engine/DefaultClockProvider
①在springboot的spring-boot-starter-web默认引入了以下依赖: <dependency> <groupId>com.fasterxml.jacks ...
- Java:并发笔记-07
Java:并发笔记-07 说明:这是看了 bilibili 上 黑马程序员 的课程 java并发编程 后做的笔记 6. 共享模型之不可变 本章内容 不可变类的使用 不可变类设计 无状态类设计 6.1 ...
随机推荐
- CISCO MDS – Useful ‘Show’ Commands
CISCO MDS – Useful ‘Show’ Commands CONFIG:show startup-configshow running-configshow running-config ...
- qmake: could not exec '/usr/lib/x86_64-linux-gnu/qt4/bin/qmake': No such file or directory
执行 qmake -v 出现错误:qmake: could not exec ‘/usr/lib/x86_64-linux-gnu/qt4/bin/qmake’: No such file or di ...
- python tkinter Text
"""小白随笔,大佬勿喷""" '''tkinter —— text''' '''可选参数有: background(bg) 文本框背景色: ...
- group by分组后获得每组中符合条件的那条记录
当group by单独使用时,只显示出每组的第一条记录.如下,未分组时查询出两条记录 SELECT info.id, info.switch_id, info.port_id, info.mac_ad ...
- ES6新特性-函数的简写(箭头函数)
通常函数的定义方法 var fn = function(...){ ...... } //例如: var add = function(a,b){ return a+b; } //或者: functi ...
- 【LeetCode每天一题】Minimum Path Sum(最短路径和)
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...
- log4cplus在VS项目中的使用
log4cplus是C++编写的开源的日志系统,宣称具有线程安全.灵活.以及多粒度控制的特点,通过将日志划分优先级使其可以面向程序调试.运行.测试.和维护等全生命周期.你可以选择将日志输出到屏幕.文件 ...
- Jenkins自动打包相关操作
Jenkins安装 Jenkins作为一个开源的集成工具,不仅可以用来进行android打包 ,也可以用来进行ios java 服务打包 官方地址https://jenkins.io/ 选择对应的系统 ...
- phpstorm----------phpstorm设置自动更新的ssh信息如何修改--后续增加如何设置自动更新
1.如何设置phpstorm将本地代码时时同步到远程服务器 注意下面一定要打勾 点击下一步,然后还有一个页面,然后不用做任何操作,直接点击完成.中途有个页面是输入远程服务器ip账号密码链接方式的,那个 ...
- 让windows10的右键菜单既显示传统cmd又显示powershell
在windows10的资源管理器中,按住shift点击右键,只显示 open powershell window here,却没有传统的cmd 解决方法就是修改注册表: HKEY_LOCAL_MACH ...