核心代码 (前提配置好文件)
@Aspect
@Component
public class LogAspect {
@Around("execution ( * com.itheima.web.controller.*.*.*(..))")
public Object aroundSysLog(ProceedingJoinPoint pjp) {
System.out.println("记录日志的方法执行了");
Object[] args = pjp.getArgs();
return pjp.proceed(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
以下是 日志记录的 AOP 环绕通知代码
package com.itheima.web.utils;
import com.itheima.common.utils.UtilFuns;
import com.itheima.domain.system.SysLog;
import com.itheima.domain.system.User;
import com.itheima.service.system.SysLogService;
import javassist.bytecode.SignatureAttribute;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
@Aspect
@Component
public class LogAspect {
@Autowired
private SysLogService sysLogService;
@Autowired
private HttpSession session;
@Autowired
private HttpServletRequest request;
@Around("execution ( * com.itheima.web.controller.*.*.*(..))")
public Object aroundSysLog(ProceedingJoinPoint pjp) {
System.out.println("记录日志的方法执行了");
try {
Signature signature = pjp.getSignature();
if (signature instanceof MethodSignature) {
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method.isAnnotationPresent(RequestMapping.class)) {
SysLog log = new SysLog();
User user = (User) session.getAttribute("user");
if (user == null || UtilFuns.isEmpty(user.getUserName())) {
log.setUserName("非法访问");
} else {
log.setUserName(user.getUserName());
log.setCompanyId(user.getCompanyId());
log.setCompanyName(user.getCompanyName());
}
log.setTime(new Date());
log.setIp(request.getRemoteAddr());
RequestMapping annotation = method.getAnnotation(RequestMapping.class);
String action = annotation.name();
log.setAction(action);
log.setMethod(method.getName());
sysLogService.save(log);
}
}
Object[] args = pjp.getArgs();
return pjp.proceed(args);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}