Java基礎,註解與自定義註解
Java 註解Annotation,是 JDK5.0 引入的一種註釋機制。
一、自帶註解
在學習自定義註解前,先了解一下Java內部定義的一套註解:共有7個,3個在java.lang中,剩下的四個在java.lang.annotation中。
作用在類或者方法上:
@Override 檢查該方法是否是重寫方法。如果發現其父類,或者是引用的接口中並沒有該方法時,會報編譯錯誤。
@Deprecated 標記已過時方法。不推薦使用
@SuppressWarnings 指示編譯器去忽略註解中聲明的警告
作用在其他註解上
@Retention 標識這個註解怎麼保存,是隻在代碼中,還是編入class文件中,或者是在運行時可以通過反射訪問。
@Documented 標記這些註解是否包含在用戶文檔中
@Target 標記這個註解應該是哪種 Java 成員
@Inherited 標記這個註解是繼承於哪個註解類(默認 註解並沒有繼承於任何子類)
額外添加的3個註解:
@SafeVarargs Java 7 開始支持,忽略任何使用參數爲泛型變量的方法或構造函數調用產生的警告。
@FunctionalInterface Java 8 開始支持,標識一個匿名函數或函數式接口。
@Repeatable Java 8 開始支持,標識某註解可以在同一個聲明上使用多次。
二、註解結構
Annotation有三個重要的主幹類,分別爲:Annotation、ElememtType、RetentionPolicy
1、Annotation:
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
2、ElementType:
其指定Annotation的類型,如METHOD ,則該Annotation只能修飾方法
public enum ElementType {
TYPE, //類、接口、枚舉
FIELD, //字段、枚舉常量
METHOD, //方法
PARAMETER, //參數
CONSTRUCTOR, //構造方法
LOCAL_VARIABLE, //局部變量
ANNOTATION_TYPE, //註釋類型
PACKAGE, //包
TYPE_PARAMETER,
TYPE_USE
}
3、RetentionPolicy:
public enum RetentionPolicy {
SOURCE, //Annotation僅存在於編譯器處理期間,編譯器處理完之後就沒有該Annotation信息了
CLASS, //編譯器將Annotation存儲於類對應的.class文件中。默認行爲
RUNTIME //編譯器將Annotation存儲於class文件中,並且可由JVM讀入
}
RUNTIME:註釋將由編譯器記錄在類文件中,並由VM在運行時保留,因此它們可以被反射讀取。
CLASS:註釋將由編譯器記錄在類文件中,但不需要在運行時由VM保留。
4、例子
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan{
}
@interface
@interface定義註解時,意味着它實現了 java.lang.annotation.Annotation 接口,即該註解就是一個Annotation。而不是聲明瞭一個interface。(@interface和interface是不同的)。
定義 Annotation 時,@interface 是必須的。
注意:它和我們通常的 implemented 實現接口的方法不同。Annotation 接口的實現細節都由編譯器完成。通過 @interface 定義註解後,該註解不能繼承其他的註解或接口。
@Document
類和方法的 Annotation 在缺省情況下是不出現在 javadoc 中的。如果使用 @Documented 修飾該 Annotation,則表示它可以出現在 javadoc 中。
@Target
ElementType 是 Annotation 的類型屬性。而 @Target 的作用,就是來指定 Annotation 的類型屬性。
@Target(ElementType.TYPE) 的意思就是指定該 Annotation 的類型是 ElementType.TYPE。這就意味着,ComponentScan 是來修飾"類、接口(包括註釋類型)或枚舉聲明"的註解。
@Retention
RetentionPolicy 是 Annotation 的策略屬性,而 @Retention 的作用,就是指定 Annotation 的策略屬性。
@Retention(RetentionPolicy.RUNTIME) 的意思就是指定該 Annotation 的策略是 RetentionPolicy.RUNTIME。這就意味着,編譯器會將該 Annotation 信息保留在 .class 文件中,並且能被虛擬機讀取。
注意:定義 Annotation 時,@Retention 可有可無。若沒有 @Retention,則默認是 RetentionPolicy.CLASS。
三、自定義Annotation
我們下面自定義一個Log日誌註解:一個 在 controller的method上的註解,該註解會將用戶對這個方法的操作 記錄到數據庫中
3.1、操作類型
package com.lee.common.enums;
/**
* 業務操作類型
*
*/
public enum BusinessType
{
/**
* 其它
*/
OTHER,
/**
* 新增
*/
INSERT,
/**
* 修改
*/
UPDATE,
/**
* 刪除
*/
DELETE,
/**
* 授權
*/
GRANT,
/**
* 導出
*/
EXPORT,
/**
* 導入
*/
IMPORT,
/**
* 強退
*/
FORCE,
/**
* 生成代碼
*/
GENCODE,
/**
* 清空數據
*/
CLEAN,
}
3.2、自定義註解
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;
/**
* 是否保存請求的參數
*/
public boolean isSaveRequestData() default true;
}
3.3、日誌處理Aspect
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);
// 配置織入點
@Pointcut("@annotation(com.lee.common.annotation.Log)")
public void logPointCut()
{
}
/**
* 處理完請求後執行
*
* @param joinPoint 切點
*/
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult)
{
handleLog(joinPoint, null, jsonResult);
}
/**
* 攔截異常操作
*
* @param joinPoint 切點
* @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;
}
// 獲取當前的用戶
LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
// *========數據庫日誌=========*//
SysOperLog operLog = new SysOperLog();
operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
// 請求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
operLog.setOperIp(ip);
// 返回參數
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));
}
// 設置方法名稱
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 設置請求方式
operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
// 處理設置註解上的參數
getControllerMethodDescription(joinPoint, controllerLog, operLog);
// 保存數據庫
AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
}
catch (Exception exp)
{
// 記錄本地異常日誌
log.error("==前置通知異常==");
log.error("異常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 獲取註解中對方法的描述信息 用於Controller層註解
*
* @param log 日誌
* @param operLog 操作日誌
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog) throws Exception
{
// 設置action動作
operLog.setBusinessType(log.businessType().ordinal());
// 設置標題
operLog.setTitle(log.title());
// 設置操作人類別
operLog.setOperatorType(log.operatorType().ordinal());
// 是否需要保存request,參數和值
if (log.isSaveRequestData())
{
// 獲取參數的信息,傳入到數據庫中。
setRequestValue(joinPoint, operLog);
}
}
/**
* 獲取請求的參數,放到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;
}
/**
* 參數拼裝
*/
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();
}
/**
* 判斷是否需要過濾的對象。
*
* @param o 對象信息。
* @return 如果是需要過濾的對象,則返回true;否則返回false。
*/
public boolean isFilterObject(final Object o)
{
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
}
}
3.4、註解的使用
/**
* 修改推薦位
*/
@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));
}
四、JoinPoint解析
1、JoinPoint
對象封裝了SpringAop切面方法中的信息
方法名 | 功能 |
---|---|
Signature getSignature(); | 獲取封裝了署名信息的對象,在該對象中可以獲取到目標方法名,所屬類的Class等信息 |
Object[] getArgs(); | 獲取傳入目標方法的參數對象 |
Object getTarget(); | 獲取被代理的對象 |
Object getThis(); | 獲取代理對象 |
joinPoint.getSignature().getName(); // 獲取目標方法名
joinPoint.getSignature().getDeclaringType().getSimpleName(); // 獲取目標方法所屬類的簡單類名
joinPoint.getSignature().getDeclaringTypeName(); // 獲取目標方法所屬類的類名
joinPoint.getSignature().getModifiers(); // 獲取目標方法聲明類型(public、private、protected)
Object[] args = joinPoint.getArgs(); // 獲取傳入目標方法的參數,返回一個數組
joinPoint.getTarget(); // 獲取被代理的對象
joinPoint.getThis(); // 獲取代理對象自己
//獲取自定義註解的信息
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
CustomLog customLog = methodSignature.getMethod().getAnnotation(CustomLog.class);
2、ProceedingJoinPoint
ProceedingJoinPoint對象是JoinPoint的子接口,該對象只用在@Around的切面方法中
Object proceed() throws Throwable //執行目標方法
Object proceed(Object[] var1) throws Throwable //傳入的新的參數去執行目標方法