⾃定义valid实现⾃定义数据校验操作1. 需要⾃定义注解 , 且指定校验class , 且具备valid注解必备的成员属性与⽅法
package com.imooc.demo.invalid;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy=ConstraintImpl.class)
public @interface Myconstraint {
/**
* 这三个⽅法是必须要有的
*/
String message();
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { }
}
1. 编写valid指定的接⼝,并实现
package com.imooc.demo.invalid;
import com.imooc.demo.rvice.UrService;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ConstraintImpl implements ConstraintValidator<Myconstraint,Object>{
@Autowired
private UrService urService;
@Override
public void initialize(Myconstraint constraintAnnotation) {
System.out.println("校验初始化...");
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
System.out.println(urService.hello());;
return true;
}
}
1. ⾃定义注解使⽤
package com.imooc.demo.curity;
import com.fasterxml.jackson.annotation.JsonView;
import com.imooc.demo.invalid.Myconstraint;
public class Ur {
@Myconstraint(message = "哈哈哈")
private String urname;
private int age;
private String password;
public interface SimpleUrInterface{}
public interface DetailUrIntereface extends SimpleUrInterface{} @JsonView(value = DetailUrIntereface.class)
public String getPassword() {
return password;
}
public void tPassword(String password) {
this.password = password;
}
public void tUrname(String urname) {
this.urname = urname;
}
public void tAge(int age) {
this.age = age;
}
@JsonView(value = SimpleUrInterface.class)
public String getUrname() {
return urname;
}
public int getAge() {
return age;
}
}