您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Java中怎么自定義注解,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
Java 注解Annotation,是 JDK5.0 引入的一種注釋機(jī)制。
在學(xué)習(xí)自定義注解前,先了解一下Java內(nèi)部定義的一套注解:共有7個(gè),3個(gè)在java.lang中,剩下的四個(gè)在java.lang.annotation中。
作用在類或者方法上:
@Override 檢查該方法是否是重寫方法。如果發(fā)現(xiàn)其父類,或者是引用的接口中并沒有該方法時(shí),會(huì)報(bào)編譯錯(cuò)誤。 @Deprecated 標(biāo)記已過時(shí)方法。不推薦使用 @SuppressWarnings 指示編譯器去忽略注解中聲明的警告
作用在其他注解上
@Retention 標(biāo)識(shí)這個(gè)注解怎么保存,是只在代碼中,還是編入class文件中,或者是在運(yùn)行時(shí)可以通過反射訪問。 @Documented 標(biāo)記這些注解是否包含在用戶文檔中 @Target 標(biāo)記這個(gè)注解應(yīng)該是哪種 Java 成員 @Inherited 標(biāo)記這個(gè)注解是繼承于哪個(gè)注解類(默認(rèn) 注解并沒有繼承于任何子類)
額外添加的3個(gè)注解:
@SafeVarargs Java 7 開始支持,忽略任何使用參數(shù)為泛型變量的方法或構(gòu)造函數(shù)調(diào)用產(chǎn)生的警告。 @FunctionalInterface Java 8 開始支持,標(biāo)識(shí)一個(gè)匿名函數(shù)或函數(shù)式接口。 @Repeatable Java 8 開始支持,標(biāo)識(shí)某注解可以在同一個(gè)聲明上使用多次。
Annotation有三個(gè)重要的主干類,分別為:Annotation、ElememtType、RetentionPolicy
public interface Annotation { boolean equals(Object obj); int hashCode(); String toString(); Class<? extends Annotation> annotationType(); }
其指定Annotation的類型,如METHOD ,則該Annotation只能修飾方法
public enum ElementType { TYPE, //類、接口、枚舉 FIELD, //字段、枚舉常量 METHOD, //方法 PARAMETER, //參數(shù) CONSTRUCTOR, //構(gòu)造方法 LOCAL_VARIABLE, //局部變量 ANNOTATION_TYPE, //注釋類型 PACKAGE, //包 TYPE_PARAMETER, TYPE_USE }
public enum RetentionPolicy { SOURCE, //Annotation僅存在于編譯器處理期間,編譯器處理完之后就沒有該Annotation信息了 CLASS, //編譯器將Annotation存儲(chǔ)于類對(duì)應(yīng)的.class文件中。默認(rèn)行為 RUNTIME //編譯器將Annotation存儲(chǔ)于class文件中,并且可由JVM讀入 }
RUNTIME:注釋將由編譯器記錄在類文件中,并由VM在運(yùn)行時(shí)保留,因此它們可以被反射讀取。
CLASS:注釋將由編譯器記錄在類文件中,但不需要在運(yùn)行時(shí)由VM保留。
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) @Documented @Repeatable(ComponentScans.class) public @interface ComponentScan{ }
@interface
@interface定義注解時(shí),意味著它實(shí)現(xiàn)了 java.lang.annotation.Annotation 接口,即該注解就是一個(gè)Annotation。而不是聲明了一個(gè)interface。(@interface和interface是不同的)。
定義 Annotation 時(shí),@interface 是必須的。
注意:它和我們通常的 implemented 實(shí)現(xiàn)接口的方法不同。Annotation 接口的實(shí)現(xiàn)細(xì)節(jié)都由編譯器完成。通過 @interface 定義注解后,該注解不能繼承其他的注解或接口。
@Document
類和方法的 Annotation 在缺省情況下是不出現(xiàn)在 javadoc 中的。如果使用 @Documented 修飾該 Annotation,則表示它可以出現(xiàn)在 javadoc 中。
@Target
ElementType 是 Annotation 的類型屬性。而 @Target 的作用,就是來指定 Annotation 的類型屬性。
@Target(ElementType.TYPE) 的意思就是指定該 Annotation 的類型是 ElementType.TYPE。這就意味著,ComponentScan 是來修飾"類、接口(包括注釋類型)或枚舉聲明"的注解。
@Retention
RetentionPolicy 是 Annotation 的策略屬性,而 @Retention 的作用,就是指定 Annotation 的策略屬性。
@Retention(RetentionPolicy.RUNTIME) 的意思就是指定該 Annotation 的策略是 RetentionPolicy.RUNTIME。這就意味著,編譯器會(huì)將該 Annotation 信息保留在 .class 文件中,并且能被虛擬機(jī)讀取。
注意:定義 Annotation 時(shí),@Retention 可有可無。若沒有 @Retention,則默認(rèn)是 RetentionPolicy.CLASS。
我們下面自定義一個(gè)Log日志注解:一個(gè) 在 controller的method上的注解,該注解會(huì)將用戶對(duì)這個(gè)方法的操作 記錄到數(shù)據(jù)庫(kù)中
package com.lee.common.enums; /** * 業(yè)務(wù)操作類型 * */ public enum BusinessType { /** * 其它 */ OTHER, /** * 新增 */ INSERT, /** * 修改 */ UPDATE, /** * 刪除 */ DELETE, /** * 授權(quán) */ GRANT, /** * 導(dǎo)出 */ EXPORT, /** * 導(dǎo)入 */ IMPORT, /** * 強(qiáng)退 */ FORCE, /** * 生成代碼 */ GENCODE, /** * 清空數(shù)據(jù) */ CLEAN, }
package com.lee.common.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.lee.common.enums.BusinessType; import com.lee.common.enums.OperatorType; /** * 自定義操作日志記錄注解 */ @Target({ ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Log { /** * 模塊 */ public String title() default ""; /** * 功能 */ public BusinessType businessType() default BusinessType.OTHER; /** * 操作人類別 */ public OperatorType operatorType() default OperatorType.MANAGE; /** * 是否保存請(qǐng)求的參數(shù) */ public boolean isSaveRequestData() default true; }
package com.lee.framework.aspectj; import java.lang.reflect.Method; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.HandlerMapping; import com.alibaba.fastjson.JSON; import com.lee.common.annotation.Log; import com.lee.common.core.domain.model.LoginUser; import com.lee.common.enums.BusinessStatus; import com.lee.common.enums.HttpMethod; import com.lee.common.utils.ServletUtils; import com.lee.common.utils.StringUtils; import com.lee.common.utils.ip.IpUtils; import com.lee.common.utils.spring.SpringUtils; import com.lee.framework.manager.AsyncManager; import com.lee.framework.manager.factory.AsyncFactory; import com.lee.framework.web.service.TokenService; import com.lee.system.domain.SysOperLog; /** * 操作日志記錄處理 * * @author lee */ @Aspect @Component public class LogAspect { private static final Logger log = LoggerFactory.getLogger(LogAspect.class); // 配置織入點(diǎn) @Pointcut("@annotation(com.lee.common.annotation.Log)") public void logPointCut() { } /** * 處理完請(qǐng)求后執(zhí)行 * * @param joinPoint 切點(diǎn) */ @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult") public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) { handleLog(joinPoint, null, jsonResult); } /** * 攔截異常操作 * * @param joinPoint 切點(diǎn) * @param e 異常 */ @AfterThrowing(value = "logPointCut()", throwing = "e") public void doAfterThrowing(JoinPoint joinPoint, Exception e) { handleLog(joinPoint, e, null); } protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) { try { // 獲得注解 Log controllerLog = getAnnotationLog(joinPoint); if (controllerLog == null) { return; } // 獲取當(dāng)前的用戶 LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest()); // *========數(shù)據(jù)庫(kù)日志=========*// SysOperLog operLog = new SysOperLog(); operLog.setStatus(BusinessStatus.SUCCESS.ordinal()); // 請(qǐng)求的地址 String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); operLog.setOperIp(ip); // 返回參數(shù) operLog.setJsonResult(JSON.toJSONString(jsonResult)); operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); if (loginUser != null) { operLog.setOperName(loginUser.getUsername()); } if (e != null) { operLog.setStatus(BusinessStatus.FAIL.ordinal()); operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); } // 設(shè)置方法名稱 String className = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); operLog.setMethod(className + "." + methodName + "()"); // 設(shè)置請(qǐng)求方式 operLog.setRequestMethod(ServletUtils.getRequest().getMethod()); // 處理設(shè)置注解上的參數(shù) getControllerMethodDescription(joinPoint, controllerLog, operLog); // 保存數(shù)據(jù)庫(kù) AsyncManager.me().execute(AsyncFactory.recordOper(operLog)); } catch (Exception exp) { // 記錄本地異常日志 log.error("==前置通知異常=="); log.error("異常信息:{}", exp.getMessage()); exp.printStackTrace(); } } /** * 獲取注解中對(duì)方法的描述信息 用于Controller層注解 * * @param log 日志 * @param operLog 操作日志 * @throws Exception */ public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog) throws Exception { // 設(shè)置action動(dòng)作 operLog.setBusinessType(log.businessType().ordinal()); // 設(shè)置標(biāo)題 operLog.setTitle(log.title()); // 設(shè)置操作人類別 operLog.setOperatorType(log.operatorType().ordinal()); // 是否需要保存request,參數(shù)和值 if (log.isSaveRequestData()) { // 獲取參數(shù)的信息,傳入到數(shù)據(jù)庫(kù)中。 setRequestValue(joinPoint, operLog); } } /** * 獲取請(qǐng)求的參數(shù),放到log中 * * @param operLog 操作日志 * @throws Exception 異常 */ private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception { String requestMethod = operLog.getRequestMethod(); if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) { String params = argsArrayToString(joinPoint.getArgs()); operLog.setOperParam(StringUtils.substring(params, 0, 2000)); } else { Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000)); } } /** * 是否存在注解,如果存在就獲取 */ private Log getAnnotationLog(JoinPoint joinPoint) throws Exception { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(Log.class); } return null; } /** * 參數(shù)拼裝 */ private String argsArrayToString(Object[] paramsArray) { String params = ""; if (paramsArray != null && paramsArray.length > 0) { for (int i = 0; i < paramsArray.length; i++) { if (!isFilterObject(paramsArray[i])) { Object jsonObj = JSON.toJSON(paramsArray[i]); params += jsonObj.toString() + " "; } } } return params.trim(); } /** * 判斷是否需要過濾的對(duì)象。 * * @param o 對(duì)象信息。 * @return 如果是需要過濾的對(duì)象,則返回true;否則返回false。 */ public boolean isFilterObject(final Object o) { return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse; } }
/** * 修改推薦位 */ @Log(title = "推薦位", businessType = BusinessType.UPDATE) @PutMapping("/edit") public AjaxResult edit(@RequestBody GsRecommPosition gsRecommPosition) { Long gsRecommPositionId = gsRecommPosition.getGsRecommPositionId(); boolean condition = recommPositionHasCategory(gsRecommPositionId); return toAjax(gsRecommPositionService.updateGsRecommPosition(gsRecommPosition)); } /** * 刪除推薦位 */ @Log(title = "推薦位", businessType = BusinessType.DELETE) @DeleteMapping("delete/{gsRecommPositionId}") public AjaxResult remove(@PathVariable Long gsRecommPositionId) { boolean condition = recommPositionHasCategory(gsRecommPositionId); return toAjax(gsRecommPositionService.deleteGsRecommPositionById(gsRecommPositionId)); }
對(duì)象封裝了SpringAop切面方法中的信息
方法名 | 功能 |
---|---|
Signature getSignature(); | 獲取封裝了署名信息的對(duì)象,在該對(duì)象中可以獲取到目標(biāo)方法名,所屬類的Class等信息 |
Object[] getArgs(); | 獲取傳入目標(biāo)方法的參數(shù)對(duì)象 |
Object getTarget(); | 獲取被代理的對(duì)象 |
Object getThis(); | 獲取代理對(duì)象 |
joinPoint.getSignature().getName(); // 獲取目標(biāo)方法名 joinPoint.getSignature().getDeclaringType().getSimpleName(); // 獲取目標(biāo)方法所屬類的簡(jiǎn)單類名 joinPoint.getSignature().getDeclaringTypeName(); // 獲取目標(biāo)方法所屬類的類名 joinPoint.getSignature().getModifiers(); // 獲取目標(biāo)方法聲明類型(public、private、protected) Object[] args = joinPoint.getArgs(); // 獲取傳入目標(biāo)方法的參數(shù),返回一個(gè)數(shù)組 joinPoint.getTarget(); // 獲取被代理的對(duì)象 joinPoint.getThis(); // 獲取代理對(duì)象自己 //獲取自定義注解的信息 MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); CustomLog customLog = methodSignature.getMethod().getAnnotation(CustomLog.class);
ProceedingJoinPoint對(duì)象是JoinPoint的子接口,該對(duì)象只用在@Around的切面方法中
Object proceed() throws Throwable //執(zhí)行目標(biāo)方法 Object proceed(Object[] var1) throws Throwable //傳入的新的參數(shù)去執(zhí)行目標(biāo)方法
關(guān)于Java中怎么自定義注解就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。