在springmvc中使用系統日誌,記錄service服務層的詳細功能調用,springmvcservice
思路:
aop :利用aop的橫切面的思路,在每個service中的方法執行之後,執行一個日誌儲存的功能.
具體步驟:
1.先定義一個日誌模型,定義需要儲存哪些日誌操作資訊.
2.編寫mapper介面,定義日誌的CRUD或其他的功能
3.配置mapper對應檔的各種sql查詢以及查詢結果中的列與對象屬性的對應,完成對象與資料庫的映射.
4.編寫service服務層代碼,封裝mapper(Dao)的功能.
5.編寫LogUtil類,,定義WriteLog(JoinPoint jp)方法,JoinPoint jp為spring在這個方法調用時為我們傳遞,即連接點.
[注:
切麵包括以下部分:
* 切入點 (在哪裡做事情)
* 通知 (增強)
* 連接點 (切入時的上下文資訊)
]
接下來,就在該方法內擷取當前執行的方法的各種資訊,並封裝到我們的日誌模型中,並持久化到資料庫中.
具體代碼:
package com.tab.crm.utils;import java.util.Date;import org.aspectj.lang.JoinPoint;import com.tab.crm.domain.SystemLog;import com.tab.crm.service.ISystemLogService;public class SystemLogUtils { // 注入日誌的services private ISystemLogService service; public void setService(ISystemLogService service) { this.service = service; } // 日誌寫入方法 @SuppressWarnings("rawtypes") public void writeLog(JoinPoint jp) { // 擷取當前方法所在的對象 Object targetObj = jp.getTarget(); // 如果進入了log的service中則退出該方法,解決死迴圈 if (targetObj instanceof ISystemLogService) { return; } // System.out.println(jp.getClass()); // System.out.println(jp.getKind()); // System.out.println(jp.getThis()); SystemLog log = new SystemLog(); //使用封裝了自訂的ActionContext的UserContext擷取當前session中的user對象 log.setOpUser(UserContext.getUser()); //使用封裝了自訂的ActionContext的UserContext擷取當前request中的ip地址 log.setOpIp(UserContext.getOpIp()); log.setOpTime(new Date()); // 擷取當前的正在執行的service類 Class serviceClz = jp.getTarget().getClass(); // 擷取當前的正在執行的方法名 String methodName = jp.getSignature().getName(); log.setFunction(serviceClz.getName() + "." + methodName); service.save(log); }}