版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35706771/article/details/82956230
Hibernate Validator
- 定义 Annotation 文件
@Target( {ElementType.METHOD, ElementType.FIELD} ) //标注在方法和属性上
@Retention( RetentionPolicy.RUNTIME) //运行时
@Constraint( validatedBy = MyConstraintValidator.class) //注解处理类
public @interface MyConstraint {
String message() default "{org.hibernate.validator.constraints.Length.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
- 定义注解处理类
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
/*
* ConstraintValidator<MyConstraint(验证哪个注解), Object(对那些数据类型进行验证)>
* */
@Resource
private HelloService helloService; //服务层
@Override
public void initialize(MyConstraint constraintAnnotation) {
// TODO Auto-generated method stub
System.out.println("自定义数据验证处理类的初始化...");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
System.out.println(value);
// HelloService.greeting("tom");
/**
* 根据返回的 true / false 来判定是否验证通过
*/
// HelloService helloService = new HelloServiceImpl();
helloService.greeting("tom");
return true;
}
}
- 实体类添加注解
@MyConstraint( message="这是一个测试验证注解" )
private Integer id;
附加内容:@JsonView
/**
* @JsonView 使用步骤
* 1、使用接口来声明多个视图
* 2、在值对象的get方法上指定视图
* 3、在Controller方法上指定视图
*/
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {};
@JsonView(UserSimpleView.class)
public String getUsername() {
return username;
}
@JsonView(UserSimpleView.class)
public Date getBirthday() {
return birthday;
}
@JsonView(UserDetailView.class)
public Integer getId() {
return id;
}
@GetMapping( value="/{id:\\d+}")
@JsonView(User.UserDetailView.class) //声明
public User getInfo(@PathVariable Integer id) {
System.out.println(id);
User user = new User(id,"idUsername","idPassword");
return user;
}