SpringBoot实体类验证注解

Hibernate Validator

  1. 定义 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[] payload() default { };
}
  1. 定义注解处理类
public class MyConstraintValidator implements ConstraintValidator {
	/*
	 * ConstraintValidator
	 * */
	
	@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;
	}

}
  1. 实体类添加注解
	@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;
	}

你可能感兴趣的:(springBoot)