自定義的註解校驗器的實現
首先先學習一下註解,註解為我們在程式碼中新增資訊提供了一種形式化的方法,使得我們在稍後的某個時刻可以方便地使用這些資料。
在日常的編碼中我們一直都在使用註解,只是沒有特別關注過,Java中內建了三種註解:@Override,@SuppressWarnings @Deprecated。相信只要學習過Java的同學一定是見過這些主角的 。
如果我們要寫一個自定義的註解應該怎麼呢?
首先需要定義一個註解標註出是自定義的註解
Java程式碼- /**
- *
- * @author zhangwei_david
-
* @version $Id: CustomerRule.java, v 0.1 2015年5月29日 下午10:12:16 zhangwei_david Exp $
- */
- @Documented
- @Target(ElementType.ANNOTATION_TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface CustomerValidator {
- }
自定義 日期型別校驗器的註解
Java程式碼- /**
- *
- * @author zhangwei_david
-
* @version $Id: Date.java, v 0.1 2015年5月29日 下午10:00:20 zhangwei_david Exp $
- */
- @Documented
- @Target(ElementType.FIELD)
- @Retention(RetentionPolicy.RUNTIME)
- @CustomerValidator
- public @interface DateString {
- String pattern() default "yyyy-MM-dd HH:mm:ss";
- String errorCode() default "must date";
- String message() default "must be date pattern";
-
}
, @Target是用來定義該註解將可以應用在什麼地方,FIELD表示該註解應用在一個屬性上,@Rectetion 用來定義該註解在哪一個級別可以使用 RUNTIME表示執行時。
String pattern() default "yyyy-MM-dd HH:mm:ss" 表示如果不指定pattern這個值的時候將返回預設值“yyyy-MM-dd HH:mm:ss” 。
有了自己的註解,那麼就需要一個註解的處理器,定義一個處理器接
Java程式碼- /**
- *自定義註解處理器介面
- *
- * @author zhangwei_david
- * @version $Id: CustomerValidatorRule.java, v 0.1 2015年5月30日 上午8:51:52 zhangwei_david Exp $
- */
- public interface CustomerValidatorRule {
- /**
- * 判斷是否支援該註解
- *
- * @param annotation
- * @param property
- * @return
- */
- public boolean support(Annotation annotation);
- /**
- * 校驗處理
- *
- *
- * @param annotation
- * @param field
- * @param errors
- */
- public void valid(Annotation annotation, Object object, Field field, Errors errors)
- throws Exception;
- }
- /**
- *
- * @author zhangwei_david
- * @version $Id: AbastractCustomerValidatorRule.java, v 0.1 2015年5月30日 上午11:22:19 zhangwei_david Exp $
- */
- public abstract class AbastractCustomerValidatorRule implements CustomerValidatorRule {
- /**
- * @see com.cathy.core.service.annotation.rule.CustomerValidatorRule#support(java.lang.annotation.Annotation)
- */
- public abstract boolean support(Annotation annotation);
- /**
- * @param <T>
- * @see com.cathy.core.service.annotation.rule.CustomerValidatorRule#valid(java.lang.annotation.Annotation, java.lang.reflect.Field, org.springframework.validation.Errors)
- */
- public void valid(Annotation annotation, Object target, final Field field, final Errors errors)
- throws Exception {
- preHandle(annotation, target, field, errors);
- PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(target.getClass(),
- field.getName());
- Method reader = propertyDescriptor.getReadMethod();
- Object property = reader.invoke(target);
- validProperty(annotation, property, new PostHandler() {
- public void postHanle(String errorCode, String message) {
- errors.rejectValue(field.getName(), errorCode, message);
- }
- });
- }
- public static interface PostHandler {
- public void postHanle(String errorCode, String message);
- }
- /**
- *
- */
- private void preHandle(Annotation annotation, Object target, Field field, Errors errors) {
- Assert.notNull(target);
- Assert.notNull(annotation);
- Assert.notNull(errors);
- Assert.notNull(field);
- }
- public abstract void validProperty(Annotation annotation, Object property,
- PostHandler postHandler);
- }
- /**
- *
- * @author zhangwei_david
- * @version $Id: DateValidatorRule.java, v 0.1 2015年5月30日 上午11:17:09 zhangwei_david Exp $
- */
- @CustomerRule
- public class DateValidatorRule extends AbastractCustomerValidatorRule {
- /**
- * @see com.cathy.core.service.annotation.rule.CustomerValidatorRule#support(java.lang.annotation.Annotation, java.lang.Object)
- */
- @Override
- public boolean support(Annotation annotation) {
- return annotation instanceof DateString;
- }
- /**
- * @see com.cathy.core.service.annotation.rule.AbastractCustomerValidatorRule#validProperty(java.lang.annotation.Annotation, java.lang.Object)
- */
- @Override
- public void validProperty(Annotation annotation, Object property, PostHandler postHandler) {
- DateString ds = (DateString) annotation;
- if (parse(ds.pattern(), (String) property) == null) {
- postHandler.postHanle(ds.errorCode(), ds.message());
- }
- }
- private Date parse(String pattern, String property) {
- try {
- SimpleDateFormat sdf = new SimpleDateFormat(pattern);
- return sdf.parse(property);
- } catch (ParseException e) {
- //do noting
- }
- return null;
- }
- }
這樣我們就有了一個註解處理器,為了方便擴充套件,該處使用註解的方式載入定義的註解處理器,這就需要定義一個標註是自定義的註解處理器的註解。
Java程式碼- /**
- *
- * @author zhangwei_david
- * @version $Id: CustomerValidatorRule.java, v 0.1 2015年5月30日 下午12:51:20 zhangwei_david Exp $
- */
- @Documented
- @Target(ElementType.TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- @Component
- public @interface CustomerRule {
- }
- /**
- *
- * @author zhangwei_david
- * @version $Id: CustomerValidatorProcesser.java, v 0.1 2015年5月30日 下午12:38:33 zhangwei_david Exp $
- */
- public class CustomerValidatorConfig implements ApplicationContextAware {
- private Map<Annotation, CustomerValidatorRule> rules = new ConcurrentHashMap<Annotation, CustomerValidatorRule>();
- Map<String, Object> customerValidationRules = null;
- /**
- * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
- */
- public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
- customerValidationRules = applicationContext
- .getBeansWithAnnotation(CustomerRule.class);
- System.out.println(customerValidationRules);
- }
- private CustomerValidatorRule findFormMap(Annotation annotation) {
- for (Entry<String, Object> entry : customerValidationRules.entrySet()) {
- if (entry.getValue() != null
- && ((CustomerValidatorRule) entry.getValue()).support(annotation)) {
- return (CustomerValidatorRule) entry.getValue();
- }
- }
- return null;
- }
- public CustomerValidatorRule findRule(Annotation annotation) {
- CustomerValidatorRule customerValidatorRule = null;
- if (!rules.containsKey(annotation)) {
- CustomerValidatorRule cvr = findFormMap(annotation);
- if (cvr != null) {
- rules.put(annotation, cvr);
- }
- customerValidatorRule = cvr;
- }
- customerValidatorRule = rules.get(annotation);
- return customerValidatorRule;
- }
- }
- /**
- *
- * @author zhangwei_david
- * @version $Id: CustomerValidatorFactory.java, v 0.1 2015年5月30日 下午1:03:56 zhangwei_david Exp $
- */
- @Component
- public class CustomerValidatorFactory implements Validator {
- @Autowired
- private CustomerValidatorConfig customerValidatorConfig;
- /**
- * @see org.springframework.validation.Validator#supports(java.lang.Class)
- */
- public boolean supports(Class<?> clazz) {
- return true;
- }
- /**
- * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
- */
- public void validate(Object target, Errors errors) {
- Assert.notNull(target);
- Assert.notNull(errors);
- List<Field> fileds = getFields(target.getClass());
- for (Field field : fileds) {
- Annotation[] annotations = field.getAnnotations();
- for (Annotation annotation : annotations) {
- if (annotation.annotationType().getAnnotation(CustomerValidator.class) != null) {
- try {
- CustomerValidatorRule customerValidatorRule = customerValidatorConfig
- .findRule(annotation);
- if (customerValidatorRule != null) {
- customerValidatorRule.valid(annotation, target, field, errors);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
-
相關推薦
自定義一個校驗器--------------------------完成用戶註冊時候,對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