1. 程式人生 > >自定義的註解校驗器的實現

自定義的註解校驗器的實現

首先先學習一下註解,註解為我們在程式碼中新增資訊提供了一種形式化的方法,使得我們在稍後的某個時刻可以方便地使用這些資料。

    在日常的編碼中我們一直都在使用註解,只是沒有特別關注過,Java中內建了三種註解:@Override,@SuppressWarnings @Deprecated。相信只要學習過Java的同學一定是見過這些主角的 。

    如果我們要寫一個自定義的註解應該怎麼呢?

    首先需要定義一個註解標註出是自定義的註解

Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: CustomerRule.java, v 0.1 2015年5月29日 下午10:12:16 zhangwei_david Exp $
     
  5.  */  
  6. @Documented  
  7. @Target(ElementType.ANNOTATION_TYPE)  
  8. @Retention(RetentionPolicy.RUNTIME)  
  9. public @interface CustomerValidator {  
  10. }  
      這個註解中沒有任何內容,屬於標記註解

    自定義 日期型別校驗器的註解

Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: Date.java, v 0.1 2015年5月29日 下午10:00:20 zhangwei_david Exp $
     
  5.  */  
  6. @Documented  
  7. @Target(ElementType.FIELD)  
  8. @Retention(RetentionPolicy.RUNTIME)  
  9. @CustomerValidator  
  10. public @interface DateString {  
  11.     String pattern() default "yyyy-MM-dd HH:mm:ss";  
  12.     String errorCode() default "must date";  
  13.     String message() default "must be date pattern";  
  14. }  
 

, @Target是用來定義該註解將可以應用在什麼地方,FIELD表示該註解應用在一個屬性上,@Rectetion 用來定義該註解在哪一個級別可以使用 RUNTIME表示執行時。

     String pattern() default "yyyy-MM-dd HH:mm:ss" 表示如果不指定pattern這個值的時候將返回預設值“yyyy-MM-dd HH:mm:ss” 。

   有了自己的註解,那麼就需要一個註解的處理器,定義一個處理器接

Java程式碼  收藏程式碼
  1. /** 
  2.  *自定義註解處理器介面 
  3.  * 
  4.  * @author zhangwei_david 
  5.  * @version $Id: CustomerValidatorRule.java, v 0.1 2015年5月30日 上午8:51:52 zhangwei_david Exp $ 
  6.  */  
  7. public interface CustomerValidatorRule {  
  8.     /** 
  9.      * 判斷是否支援該註解 
  10.      * 
  11.      * @param annotation 
  12.      * @param property 
  13.      * @return 
  14.      */  
  15.     public boolean support(Annotation annotation);  
  16.     /** 
  17.      *  校驗處理 
  18.      *  
  19.      * 
  20.      * @param annotation 
  21.      * @param field 
  22.      * @param errors 
  23.      */  
  24.     public void valid(Annotation annotation, Object object, Field field, Errors errors)  
  25.             throws Exception;  
  26. }  
  Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: AbastractCustomerValidatorRule.java, v 0.1 2015年5月30日 上午11:22:19 zhangwei_david Exp $ 
  5.  */  
  6. public abstract class AbastractCustomerValidatorRule implements CustomerValidatorRule {  
  7.     /** 
  8.      * @see com.cathy.core.service.annotation.rule.CustomerValidatorRule#support(java.lang.annotation.Annotation) 
  9.      */  
  10.     public abstract boolean support(Annotation annotation);  
  11.     /** 
  12.      * @param <T> 
  13.      * @see com.cathy.core.service.annotation.rule.CustomerValidatorRule#valid(java.lang.annotation.Annotation, java.lang.reflect.Field, org.springframework.validation.Errors) 
  14.      */  
  15.     public void valid(Annotation annotation, Object target, final Field field, final Errors errors)  
  16.                                                                                                    throws Exception {  
  17.         preHandle(annotation, target, field, errors);  
  18.         PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(target.getClass(),  
  19.             field.getName());  
  20.         Method reader = propertyDescriptor.getReadMethod();  
  21.         Object property = reader.invoke(target);  
  22.         validProperty(annotation, property, new PostHandler() {  
  23.             public void postHanle(String errorCode, String message) {  
  24.                 errors.rejectValue(field.getName(), errorCode, message);  
  25.             }  
  26.         });  
  27.     }  
  28.     public static interface PostHandler {  
  29.         public void postHanle(String errorCode, String message);  
  30.     }  
  31.     /** 
  32.      * 
  33.      */  
  34.     private void preHandle(Annotation annotation, Object target, Field field, Errors errors) {  
  35.         Assert.notNull(target);  
  36.         Assert.notNull(annotation);  
  37.         Assert.notNull(errors);  
  38.         Assert.notNull(field);  
  39.     }  
  40.     public abstract void validProperty(Annotation annotation, Object property,  
  41.                                        PostHandler postHandler);  
  42. }  
  Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: DateValidatorRule.java, v 0.1 2015年5月30日 上午11:17:09 zhangwei_david Exp $ 
  5.  */  
  6. @CustomerRule  
  7. public class DateValidatorRule extends AbastractCustomerValidatorRule {  
  8.     /** 
  9.      * @see com.cathy.core.service.annotation.rule.CustomerValidatorRule#support(java.lang.annotation.Annotation, java.lang.Object) 
  10.      */  
  11.     @Override  
  12.     public boolean support(Annotation annotation) {  
  13.         return annotation instanceof DateString;  
  14.     }  
  15.     /** 
  16.      * @see com.cathy.core.service.annotation.rule.AbastractCustomerValidatorRule#validProperty(java.lang.annotation.Annotation, java.lang.Object) 
  17.      */  
  18.     @Override  
  19.     public void validProperty(Annotation annotation, Object property, PostHandler postHandler) {  
  20.         DateString ds = (DateString) annotation;  
  21.         if (parse(ds.pattern(), (String) property) == null) {  
  22.             postHandler.postHanle(ds.errorCode(), ds.message());  
  23.         }  
  24.     }  
  25.     private Date parse(String pattern, String property) {  
  26.         try {  
  27.             SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  28.             return sdf.parse(property);  
  29.         } catch (ParseException e) {  
  30.             //do noting  
  31.         }  
  32.         return null;  
  33.     }  
  34. }  
 

   這樣我們就有了一個註解處理器,為了方便擴充套件,該處使用註解的方式載入定義的註解處理器,這就需要定義一個標註是自定義的註解處理器的註解。

Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: CustomerValidatorRule.java, v 0.1 2015年5月30日 下午12:51:20 zhangwei_david Exp $ 
  5.  */  
  6. @Documented  
  7. @Target(ElementType.TYPE)  
  8. @Retention(RetentionPolicy.RUNTIME)  
  9. @Component  
  10. public @interface CustomerRule {  
  11. }  
  Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: CustomerValidatorProcesser.java, v 0.1 2015年5月30日 下午12:38:33 zhangwei_david Exp $ 
  5.  */  
  6. public class CustomerValidatorConfig implements ApplicationContextAware {  
  7.     private Map<Annotation, CustomerValidatorRule> rules                   = new ConcurrentHashMap<Annotation, CustomerValidatorRule>();  
  8.     Map<String, Object>                            customerValidationRules = null;  
  9.     /** 
  10.      * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext) 
  11.      */  
  12.     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
  13.         customerValidationRules = applicationContext  
  14.                 .getBeansWithAnnotation(CustomerRule.class);  
  15.         System.out.println(customerValidationRules);  
  16.     }  
  17.     private CustomerValidatorRule findFormMap(Annotation annotation) {  
  18.         for (Entry<String, Object> entry : customerValidationRules.entrySet()) {  
  19.             if (entry.getValue() != null  
  20.                     && ((CustomerValidatorRule) entry.getValue()).support(annotation)) {  
  21.                 return (CustomerValidatorRule) entry.getValue();  
  22.             }  
  23.         }  
  24.         return null;  
  25.     }  
  26.     public CustomerValidatorRule findRule(Annotation annotation) {  
  27.         CustomerValidatorRule customerValidatorRule = null;  
  28.         if (!rules.containsKey(annotation)) {  
  29.             CustomerValidatorRule cvr = findFormMap(annotation);  
  30.             if (cvr != null) {  
  31.                 rules.put(annotation, cvr);  
  32.             }  
  33.             customerValidatorRule = cvr;  
  34.         }  
  35.         customerValidatorRule = rules.get(annotation);  
  36.         return customerValidatorRule;  
  37.     }  
  38. }  
 通過實現ApplicationContextAware介面,從上下文中自動載入處理器。 Java程式碼  收藏程式碼
  1. /** 
  2.  * 
  3.  * @author zhangwei_david 
  4.  * @version $Id: CustomerValidatorFactory.java, v 0.1 2015年5月30日 下午1:03:56 zhangwei_david Exp $ 
  5.  */  
  6. @Component  
  7. public class CustomerValidatorFactory implements Validator {  
  8.     @Autowired  
  9.     private CustomerValidatorConfig customerValidatorConfig;  
  10.     /** 
  11.      * @see org.springframework.validation.Validator#supports(java.lang.Class) 
  12.      */  
  13.     public boolean supports(Class<?> clazz) {  
  14.         return true;  
  15.     }  
  16.     /** 
  17.      * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors) 
  18.      */  
  19.     public void validate(Object target, Errors errors) {  
  20.         Assert.notNull(target);  
  21.         Assert.notNull(errors);  
  22.         List<Field> fileds = getFields(target.getClass());  
  23.         for (Field field : fileds) {  
  24.             Annotation[] annotations = field.getAnnotations();  
  25.             for (Annotation annotation : annotations) {  
  26.                 if (annotation.annotationType().getAnnotation(CustomerValidator.class) != null) {  
  27.                     try {  
  28.                         CustomerValidatorRule customerValidatorRule = customerValidatorConfig  
  29.                             .findRule(annotation);  
  30.                         if (customerValidatorRule != null) {  
  31.                             customerValidatorRule.valid(annotation, target, field, errors);  
  32.                         }  
  33.                     } catch (Exception e) {  
  34.                         e.printStackTrace();  
  35.                     }  
  36.                 }  
  37.             }  
  38.         }  
  39. 相關推薦

    定義一個--------------------------完成用戶註冊時候,對username是否符合規則以及時候已經存在於數據庫的

    實例 check ajax -- value ava .cn java 數據 實例: <!-- 自定義校驗表單--> $.validator.addMethod( "checkusername", //校驗規則名稱,類似於required

    springboot定義註解時出現的異常

    異常資訊: javax.validation.ConstraintDefinitionException: HV000074 原因: 在約束註釋中它是關於groups()和payload()缺失的,只需新增這兩行就可以了: Class<?>[] groups() de

    Spring Boot系列-使用定義註解使用者是否登入

    摘要: 記得今年年初剛開始面試的時候,被問的最多的就是你知道Spring的兩大核心嘛?那你說說什麼是AOP,什麼是IOC?我相信你可能也被問了很多次了。 1、到底是什麼是AOP? 所謂AOP也就是面向切面程式設計,能夠讓我們在不影響原有業務功能的前提下,橫切擴充套件新的功能。 記得今年

    SpringBoot系列之使用定義註解使用者是否登入

    記得今年年初剛開始面試的時候,被問的最多的就是你知道Spring的兩大核心嘛?那你說說什麼是AOP,什麼是IOC?我相信你可能也被問了很多次了。 1、到底是什麼是AOP? 所謂AOP也就是面向切面程式設計,能夠讓我們在不影響原有業務功能的前提下,橫切擴充套件新的功能。這裡面有一個比較顯眼的詞

    Hibernate Validation定義註解

    權宣告:本文為博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/cccmercy/article/details/79105624 情景:需要對String型別的屬性比如description進行驗證,驗證規則是當descript

    java @Target 定義註解 引數是否為空

    第一步自定義類 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; impor

    JSR303(hibernate-validator)定義註解

    自定義註解校驗 以校驗手機號為例,自定義 @IsPhone來驗證是否是手機號: 編寫註解: //說明該註解將被包含在javadoc中 @Documented // 註解的作用目標 類上、方法上、屬性上 @Target({ElementType.FIELD,

    定義註解

    第一步 編寫class實現javax.validation.ConstraintValidator這個介面(泛型引數第二步編寫) 這裡的{zlmessage}是從模板ValidationMessages_zh_CN.properties文件鐘取值 第二步  編寫註解

    定義註解實現

    首先先學習一下註解,註解為我們在程式碼中新增資訊提供了一種形式化的方法,使得我們在稍後的某個時刻可以方便地使用這些資料。     在日常的編碼中我們一直都在使用註解,只是沒有特別關注過,Java中內建了三種註解:@Override,@SuppressWarnings @Deprecated。相信只要學習過J

    更加靈活的引數,Spring-boot定義引數註解

    上文[測試開發專題:如何在spring-boot中進行引數校驗](https://www.immortalp.com/articles/2020/05/15/1589509696197.html),我們討論瞭如何使用@Min、@Max等註解進行引數校驗,主要是針對基本資料型別和級聯物件進行引數校驗的演示,但是

    SpringSecurity 進行定義Token

    單獨 snapshot author 調試 wired vax net figure cas 背景 Spring Security默認使用「用戶名/密碼」的方式進行登陸校驗,並通過cookie的方式存留登陸信息。在一些定制化場景,比如希望單獨使用token串進行部分頁面的訪

    說說定義註解的場景及實現---------

    lin 場景 框架 .html int utm 方法 註解配置 http 說說自定義註解的場景及實現 跟蹤代碼的依賴性,實現代替配置文件的功能。比較常見的是Spring等框架中的基於註解配置。 還可以生成文檔常見的@See@param@return等。如@overrid

    Lucene筆記20-Lucene的分詞-實現定義同義詞分詞-實現分詞(良好設計方案)

    一、目前存在的問題 在getSameWords()方法中,我們使用map臨時存放了兩個鍵值對用來測試,實際開發中,往往需要很多的這種鍵值對來處理,比如從某個同義詞詞典裡面獲取值之類的,所以說,我們需要一個類,根據key提供近義詞。 為了能更好的適應應用場景,我們先定義一個介面,其中定義一

    Lucene筆記19-Lucene的分詞-實現定義同義詞分詞-實現分詞

    一、同義詞分詞器的程式碼實現 package com.wsy; import com.chenlb.mmseg4j.Dictionary; import com.chenlb.mmseg4j.MaxWordSeg; import com.chenlb.mmseg4j.analysis.MM

    spring boot整合swagger,定義註解,攔截,xss過濾,非同步呼叫,定時任務案例

    本文介紹spring boot整合swagger,自定義註解,攔截器,xss過濾,非同步呼叫,定時任務案例 整合swagger--對於做前後端分離的專案,後端只需要提供介面訪問,swagger提供了介面呼叫測試和各種註釋的視覺化web介面。配置swagger的掃描包路徑,api資訊等,見配置類Swagger

    說說定義註解的場景及實現

    登陸、許可權攔截、日誌處理,以及各種 Java 框架,如 Spring,Hibernate,JUnit 提到註解就不能不說反射,Java 自定義註解是通過執行時靠反射獲取註解。實際開發中,例如我們要獲取某個方法的呼叫日誌,可以通過 AOP(動態代理機制)給方法新

    定義一個迭代實現斐波那契數列

    class Fibiter(object): def __init__(self,n): #初始化引數 self.n = n #生成數列的前n個數 #當前數列中的第幾個數 self.cur

    java定義註解、mybatis 外掛 實現資料庫 分庫分表

    一、自定義註解實現分庫 為什麼會有資料庫切庫一說 首先,許多專案都有主庫與從庫,有的主庫後面甚至會有很多個從庫,主從庫之間的通常同步也很快,這為資料庫切庫提供了一個基礎,因為可以去不同的資料庫查詢,得到相同的結果(如果不同的資料庫是完全不同的,這個不在我們這篇文章討論的範圍之內,那個屬於讓專

    定義註解的場景及實現

    java中有四種元註解:@Retention、@Inherited、@Documented、@Target @Retention註解的保留位置(列舉RetentionPolicy),RetentionPolicy可選值: SOURCE:註解僅存在於原始碼中,在class位元組碼檔案中不包含CLASS:預設

    spring 定義引數

    Spring bean校驗 public abstract class GenericValidator { public abstract void validate(ProceedingJoinPoint pjp); protected