利用 Spring AOP 切面,在 Service 方法執行後自動記錄操作日誌(用戶、IP、時間、調用方法),無侵入業務代碼。
SystemLog (id, opUser, opIp, opTime, function...)ISystemLogServiceSystemLogUtils,實現 writeLog(JoinPoint jp)public class SystemLogUtils {
private ISystemLogService service; // 注入
public void setService(ISystemLogService service) { this.service = service; }
@SuppressWarnings("rawtypes")
public void writeLog(JoinPoint jp) {
Object target = jp.getTarget();
// 避免遞歸:若目標是日誌 Service 本身,直接返回
if (target instanceof ISystemLogService) return;
SystemLog log = new SystemLog();
log.setOpUser(UserContext.getUser()); // 從 ThreadLocal 獲取當前用戶
log.setOpIp(UserContext.getOpIp()); // 獲取請求 IP
log.setOpTime(new Date());
Class> clazz = target.getClass();
String methodName = jp.getSignature().getName();
log.setFunction(clazz.getName() + "." + methodName); // 完整方法簽名
service.save(log); // 持久化
}
}
service.save() 放入異步執行器或消息隊列,避免阻塞主業務。<bean id="systemLogUtils" class="com.tab.crm.utils.SystemLogUtils">
<property name="service" ref="systemLogService"/>
</bean>
<aop:config>
<aop:aspect ref="systemLogUtils">
<aop:pointcut id="serviceLog" expression="execution(* com.tab.crm.service..*.*(..))"/>
<aop:after-returning method="writeLog" pointcut-ref="serviceLog"/>
</aop:aspect>
</aop:config>
此方案實現「業務零侵入、日誌全覆蓋」,是审計追蹤的經典模式。