组件的验证(Bean验证)
package SpringLean.Users;
import org.springframework.beans.factory.annotation.Autowired;
// 这是我们的 用户实体类
public class UserEntity {
private int user_id;
private String user_name;
private int age;
public UserEntity(int user_id, String user_name, int age) {
this.user_id = user_id;
this.user_name = user_name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
@Autowired
public String toString(){
return "用户信息:" + this.getUser_id() + ":" + this.getUser_name() + ":" + this.getAge();
}
}
比如我们有这么一个用户实体类
,其中的属性往往是需要有个验证的:age
不能大于多少,user_name
不能包含非法字符。
当然可以在setter方法里来判断,只不过显得B格有点儿低了。
Spring框架有没有什么高级的处理验证的方式?
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#validator
package SpringLean.Users;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
// 用户验证器
@Component
public class UserValidator implements Validator {
public boolean supports(Class<?> aClass) {
// 是 UserEntity类 才验证
return UserEntity.class.equals(aClass);
}
public void validate(Object o, Errors errors) {
// 把o对象强制转化为UserEntity对象
UserEntity userEntity = (UserEntity)o;
// 开始验证
if (userEntity.getAge() < 0) {
errors.reject("age", "年龄不能小于0");
} else if (userEntity.getAge() > 110) {
errors.reject("age", "年龄不能不能大于110");
}
}
}
写一个验证器类。
如何把这个验证器类和用户实体类相关联?
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#validation-beanvalidation
还在我们的测试类MyTest
中来演示:
@Component("MyTest")
public class MyTest {
@Autowired
UserValidator userValidator; // 加载UserValidator类
// 写个方法用于检测
public void showUser(UserEntity userEntity){
// 把UserEntity和UserValidator关联后,执行验证
DataBinder dataBinder = new DataBinder(userEntity);
dataBinder.setValidator(this.userValidator);
dataBinder.validate();
if (dataBinder.getBindingResult().hasErrors()){
// 验证有错误
List<ObjectError> errors = dataBinder.getBindingResult().getAllErrors();
for (ObjectError error : errors){
System.out.println(error.getDefaultMessage());
}
}else{
System.out.println("数据验证通过");
}
}
}
上面代码可以看出:在showUser()
方法接收一个UserEntity
类对象,在该方法中进行了和验证类的关联,并且做了验证的判断处理。
来到入口文件,实例化MyTest类
并调用相关方法测试:
public static void main(String[] args) throws Exception{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("SpringLean");
context.refresh();
MyTest myTest = context.getBean("MyTest",MyTest.class);
UserEntity userEntity = new UserEntity(1,"zhangsan",120);
myTest.showUser(userEntity);
}
执行程序,控制台输出:
年龄不能不能大于110
思考:
如果我们有很多实体类,是否都需要一个个创建Validator来对期验证?
Hibernate Validator入门
JSR-303 Bean Validation API
https://docs.spring.io/spring/docs/5.0.1.BUILD-SNAPSHOT/spring-framework-reference/core.html#validation-beanvalidation-overview
这是一个规范,并不是Spring特有的,Spring框架集成了Bean Validation 1.0 (JSR-303) / 1.1 (JSR-349) / 2.0(JSR-380)
关于Bean Validation
具体可以看:
http://beanvalidation.org/
目前实现该规范的有Hibernate Validator
,文档地址:
http://hibernate.org/validator/
1、使用maven安装。
在pom.xml
文件里:
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.7.Final</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b08</version>
</dependency>
2、改造我们的用户实体类
package SpringLean.Users;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
// 这是我们的 用户实体类
public class UserEntity {
private int user_id;
@NotNull
private String user_name;
@NotNull
@Min(value = 10, message = "年龄不能小于10")
@Max(value = 110, message = "年龄不能大于110")
private int age;
public UserEntity(int user_id, String user_name, int age) {
this.user_id = user_id;
this.user_name = user_name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
@Autowired
public String toString(){
return "用户信息:" + this.getUser_id() + ":" + this.getUser_name() + ":" + this.getAge();
}
}
注意,我们在几个属性上打上了注解。
3、注册Bean
package SpringLean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration // 表明这是一个配置类
public class MyConfig {
@Bean
public Validator LocalValidator(){
return new LocalValidatorFactoryBean();
}
}
关于注册Bean的方式,这里还是使用的注解的方式,关于这部分知识,可以查看:
http://blog.csdn.net/github_26672553/article/details/78793707
4、然后我们肯定知道在MyTest
类中,就就要验证类换掉了
@Autowired
Validator LocalValidator;
dataBinder.setValidator(this.LocalValidator);
这样就完成了Hibernate Validator的简单使用。
总结:
到这一步,我们可以发现:使用Hibernate Validator的好处就是避免了单独写验证类,通过注解的形式直接在我们的实体类上就可以完成了