零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> OpenGL ES 特效 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> O ...
使用Spring AOP實現系統操作日誌記錄
一、什麼是Spring
Spring 是一個廣泛應用的J2EE框架,是針對bean的生命周期進行管理的輕量級容器,主要由Spring Core、Spring AOP、Spring ORM、Spring DAO、Spring Context、Spring Web、Spring Web MVC七大模塊組成。
二、什麼是AOP
AOP是Aspect Oriented Programming的縮寫,是面向切麵編程,針對業務處理過程中的切麵進行提取,降低了耦合度,提高了可重用性,經常用於日誌記錄、性能統計、安全控制、事務處理、異常處理等。AOP分為靜態代理和動態代理,常見的AOP實現有AspectJ,Spring AOP,其中Aspect是屬於靜態代理,Spring AOP是動態代理,Spring AOP實現又是採用的JDK動態代理和CGLib動態代理兩種方式。
三、相關術語
Aspect: 切麵,在Spring中使用@Aspect註解標識,該類封裝一些具體的操作,例如記錄日誌。
Joinpoint: 連接點,是指的是在程式運行過程中的某個階段。
Pointcut: 切入點,定義的一個或者一組方法,當程式執行到這些切入點時,會產生通知。
@Before: 前置通知,在連接點之前執行的通知,不能阻止連接點前的執行。
@AfterReturning: 在連接點正常完成後執行的通知,不拋出異常的情況。
@AfterThrowing: 和上方剛好補充,在連接點拋出異常是執行的通知。
@After: 在連接點退出時執行的通知。異常退出和正常退出都會執行。
@Around: 環繞通知,可以在方法前後加入自定義的操作,相當於環繞包圍,並且可以決定方法是否執行。
四、代碼實現
@Aspect
@Component
@Slf4j
public class SysLogAspect {
/**
* Controller層切點,SysLog是自定義的註解
*/
@Pointcut("@annotation(com.xxx.xxx.SysLog)")
public void SysLogPointAspect() {
}
/**
* @Description 環繞通知 用於攔截Controller層記錄用戶的操作
*/
@Around("SysLogPointAspect()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
//*========控制台輸出=========*//
log.info("==============訪問請求==============\n");
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String requireType = request.getMethod();
String requireUrl = request.getRequestURI();
// 獲取註解信息
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
SysLog syslog = method.getAnnotation(SysLog.class);
//*========資料庫日誌=========*//
// 保存日誌到資料庫.....
// 方法執行開始
long beginTime = System.currentTimeMillis();
//執行方法
Object result = joinPoint.proceed();
//執行時長(毫秒)
long execTime = System.currentTimeMillis() - beginTime;
return result;
}
}