1. 程式人生 > >SpringBoot實體類驗證註解

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<? extends Payload>[] payload() default { };
}
  1. 定義註解處理類
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;
	}

}
  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;
	}