Spring 自定義注解玩法大全,從入門(mén)到…
閱讀本文大概需要 5 分鐘。
作者:何甜甜在嗎
鏈接:https://juejin.im/post/5cf376e16fb9a07eee5eb6eb
字段注解
hibernate-validate依賴就提供了很多校驗(yàn)注解 ,如@NotNull、@Range等,但是這些注解并不是能夠滿足所有業(yè)務(wù)場(chǎng)景的。String集合中,那么已有的注解就不能滿足需求了,需要自己實(shí)現(xiàn)。自定義注解
@Check注解,通過(guò)@interface聲明一個(gè)注解@Target({?ElementType.FIELD})?//只允許用在類的字段上
@Retention(RetentionPolicy.RUNTIME)?//注解保留在程序運(yùn)行期間,此時(shí)可以通過(guò)反射獲得定義在某個(gè)類上的所有注解
@Constraint(validatedBy?=?ParamConstraintValidated.class)
public?@interface?Check?{
????/**
?????*?合法的參數(shù)值
?????*?*/
????String[]?paramValues();
????/**
?????*?提示信息
?????*?*/
????String?message()?default?"參數(shù)不為指定值";
????Class>[]?groups()?default?{};
????Class?extends?Payload>[]?payload()?default?{};
}
ElementType.TYPE:說(shuō)明該注解只能被聲明在一個(gè)類前。ElementType.FIELD:說(shuō)明該注解只能被聲明在一個(gè)類的字段前。ElementType.METHOD:說(shuō)明該注解只能被聲明在一個(gè)類的方法前。ElementType.PARAMETER:說(shuō)明該注解只能被聲明在一個(gè)方法參數(shù)前。ElementType.CONSTRUCTOR:說(shuō)明該注解只能聲明在一個(gè)類的構(gòu)造方法前。ElementType.LOCAL_VARIABLE:說(shuō)明該注解只能聲明在一個(gè)局部變量前。ElementType.ANNOTATION_TYPE:說(shuō)明該注解只能聲明在一個(gè)注解類型前。ElementType.PACKAGE:說(shuō)明該注解只能聲明在一個(gè)包名前RetentionPolicy.SOURCE: 注解只保留在源文件中?RetentionPolicy.CLASS?: 注解保留在class文件中,在加載到JVM虛擬機(jī)時(shí)丟棄RetentionPolicy.RUNTIME: 注解保留在程序運(yùn)行期間,此時(shí)可以通過(guò)反射獲得定義在某個(gè)類上的所有注解。驗(yàn)證器類
ConstraintValidator泛型接口Check:注解,第二個(gè)泛型參數(shù)Object:校驗(yàn)字段類型。需要實(shí)現(xiàn)initialize和isValid方法,isValid方法為校驗(yàn)邏輯,initialize方法初始化工作使用方式
@Data
public?class?User?{
????/**
?????*?姓名
?????*?*/
????private?String?name;
????/**
?????*?性別?man?or?women
?????*?*/
????@Check(paramValues?=?{"man",?"woman"})
????private?String?sex;
}
sex字段加校驗(yàn),其值必須為woman或者man測(cè)試
@RestController("/api/test")
public?class?TestController?{
????@PostMapping
????public?Object?test(@Validated?@RequestBody?User?user)?{
????????return?"hello?world";
????}
}
User對(duì)象上加上@Validated注解,這里也可以使用@Valid注解,@Validated 和 @Valid 的區(qū)別,這篇建議看下。方法、類注解
guava cache中查找,在從redis查找,最后查找mysql(多級(jí)緩存)。spring-data-redis包下類似@Cacheable的注解。權(quán)限注解
自定義注解
@Target({?ElementType.METHOD,?ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public?@interface?PermissionCheck?{
????/**
?????*?資源key
?????*?*/
????String?resourceKey();
}
攔截器類
public?class?PermissionCheckInterceptor?extends?HandlerInterceptorAdapter?{
????/**
?????*?處理器處理之前調(diào)用
?????*/
????@Override
????public?boolean?preHandle(HttpServletRequest?request,?HttpServletResponse?response,
?????????????????????????????Object?handler)?throws?Exception?{
????????HandlerMethod?handlerMethod?=?(HandlerMethod)handler;
????????PermissionCheck?permission?=?findPermissionCheck(handlerMethod);
????????//如果沒(méi)有添加權(quán)限注解則直接跳過(guò)允許訪問(wèn)
????????if?(permission?==?null)?{
????????????return?true;
????????}
????????//獲取注解中的值
????????String?resourceKey?=?permission.resourceKey();
????????//TODO?權(quán)限校驗(yàn)一般需要獲取用戶信息,通過(guò)查詢數(shù)據(jù)庫(kù)進(jìn)行權(quán)限校驗(yàn)
????????//TODO?這里只進(jìn)行簡(jiǎn)單演示,如果resourceKey為testKey則校驗(yàn)通過(guò),否則不通過(guò)
????????if?("testKey".equals(resourceKey))?{
????????????return?true;
????????}
????????return?false;
????}
????/**
?????*?根據(jù)handlerMethod返回注解信息
?????*
?????*?@param?handlerMethod?方法對(duì)象
?????*?@return?PermissionCheck注解
?????*/
????private?PermissionCheck?findPermissionCheck(HandlerMethod?handlerMethod)?{
????????//在方法上尋找注解
????????PermissionCheck?permission?=?handlerMethod.getMethodAnnotation(PermissionCheck.class);
????????if?(permission?==?null)?{
????????????//在類上尋找注解
????????????permission?=?handlerMethod.getBeanType().getAnnotation(PermissionCheck.class);
????????}
????????return?permission;
????}
}
true,否則返回false測(cè)試
?@GetMapping("/api/test")
?@PermissionCheck(resourceKey?=?"test")
?public?Object?testPermissionCheck()?{
?????return?"hello?world";
?}
PermissionCheck注解。緩存注解
自定義注解
@Target({?ElementType.METHOD,?ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public?@interface?CustomCache?{
????/**
?????*?緩存的key值
?????*?*/
????String?key();
}
切面
@Aspect
@Component
public?class?CustomCacheAspect?{
????/**
?????*?在方法執(zhí)行之前對(duì)注解進(jìn)行處理
?????*
?????*?@param?pjd
?????*?@param?customCache?注解
?????*?@return?返回中的值
?????*?*/
????@Around("@annotation(com.cqupt.annotation.CustomCache)?&&?@annotation(customCache)")
????public?Object?dealProcess(ProceedingJoinPoint?pjd,?CustomCache?customCache)?{
????????Object?result?=?null;
????????if?(customCache.key()?==?null)?{
????????????//TODO?throw?error
????????}
????????//TODO?業(yè)務(wù)場(chǎng)景會(huì)比這個(gè)復(fù)雜的多,會(huì)涉及參數(shù)的解析如key可能是#{id}這些,數(shù)據(jù)查詢
????????//TODO?這里做簡(jiǎn)單演示,如果key為testKey則返回hello?world
????????if?("testKey".equals(customCache.key()))?{
????????????return?"hello?word";
????????}
????????//執(zhí)行目標(biāo)方法
????????try?{
????????????result?=?pjd.proceed();
????????}?catch?(Throwable?throwable)?{
????????????throwable.printStackTrace();
????????}
????????return?result;
????}
}
測(cè)試
@GetMapping("/api/cache")
@CustomCache(key?=?"test")
public?Object?testCustomCache()?{
????return?"don't?hit?cache";
}
推薦閱讀:
用數(shù)據(jù)庫(kù)實(shí)現(xiàn)了一個(gè)分布式鎖,雖簡(jiǎn)陋,但能用!
微信掃描二維碼,關(guān)注我的公眾號(hào)
朕已閱?

