之前看日誌裏面有用到aop的技術所以想照着做一個過程如下
1創建一個@interface文件
package io.sirc.common.annotation;
import java.lang.annotation.*;
/**
* 系統日誌註解
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SysQueryLog {
String value() default "";
}
2創建一個調用它的類,注意其中地址指向io.sirc.common.annotation.SysQueryLog是前面那貨的地址
package io.sirc.common.aspect;
import io.sirc.common.utils.HttpContextUtils;
import io.sirc.common.utils.IPUtils;
import io.sirc.common.utils.R;
import io.sirc.modules.sea.entity.GetDataResponse;
import io.sirc.modules.sys.entity.SysQueryLogEntity;
import io.sirc.modules.sys.entity.SysUserEntity;
import io.sirc.modules.sys.service.SysQueryLogService;
import io.sirc.modules.sys.service.SysUserService;
import net.sf.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* 系統日誌,切面處理類
*
*/
@Aspect
@Component
public class SysQueryLogAspect {
@Value("${isLocal}")
private boolean isLocal;
@Autowired
private SysQueryLogService sysQueryLogService;
@Autowired
private SysUserService sysUserService;
@Pointcut("@annotation(io.sirc.common.annotation.SysQueryLog)")
public void logPointCut() {
}
}
3.在SysQueryLogAspect 中添加方法,當然可以使用好幾種標籤@before,@after之類的 因爲我現在需要的是進來之前判斷參數中是否含有某些值 ,如果存在則中斷不執行,執行方法後在執行日誌插入操作,就使用@Around了,這樣一下倆都能實現,
其中point是傳進方法的參數,result是返回回去的值 ,point.proceed()是執行需要的接口,寫在這上面的是調用接口之前執行的方法,寫在下面的是執行之後的方法
@Around("logPointCut()")
public GetDataResponse around(ProceedingJoinPoint point) throws Throwable {
GetDataResponse result = new GetDataResponse();
long beginTime = System.currentTimeMillis();
//執行時長(毫秒)
JSONObject jo = getParam(point);
if(!isQueryLock(jo)) {
result.setData(new R().ok().put("message","當前賬號和ip已被鎖定,請稍後再試。").toString());
return result;
}
if(!isCompatible(jo)) {
result.setData(new R().ok().put("message","當前賬號和ip不匹配").toString());
return result;
}
result= (GetDataResponse) point.proceed();
long time = System.currentTimeMillis() - beginTime;
saveSysQueryLog(jo, time);
return result;
}
4.在接口前面加上標籤
@SysQueryLog
public GetDataResponse getDataRequest(@RequestParam Map<String, Object> params) {
//執行接口代碼~~~~~~~~~~~~~~~~~
}