日志增强类
package com.service;
import com.dao.LogMapper;
import com.model.SysLog;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;
@Component
@Aspect
public class LogAop {
private Date visitedTime;
private Class visitedClass;
private Method visitedMethod;
private String method;
private long executionTime;
@Autowired
private HttpServletRequest request;
@Autowired
private LogMapper mapper;
@Before("execution(* com.controller.*Controller.*(..))")
public void before(JoinPoint joinPoint) throws NoSuchMethodException {
visitedTime = new Date();
visitedClass=joinPoint.getTarget().getClass();
String methodName = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
if (args==null ||args.length == 0){
visitedMethod=visitedClass.getMethod(methodName);
}else {
Class[] argsClass = new Class[args.length];
for(int i = 0;i<args.length;i++){
argsClass[i] = args[i].getClass();
}
visitedMethod = visitedClass.getMethod(methodName, argsClass);
}
method = visitedClass.getName()+"."+visitedMethod.getName();
}
@After("execution(* com.controller.*Controller.*(..))")
public void after(JoinPoint joinPoint){
executionTime = new Date().getTime() - visitedTime.getTime();
String ip = request.getRemoteAddr();
SecurityContext securityContext = SecurityContextHolder.getContext();
String username = ((User) (securityContext.getAuthentication().getPrincipal())).getUsername();
RequestMapping classAnnotation = (RequestMapping)visitedClass.getAnnotation(RequestMapping.class);
String[] classUrl = classAnnotation.value();
String[] methodUrl = visitedMethod.getAnnotation(RequestMapping.class).value();
String url = classUrl[0]+methodUrl[0];
SysLog sysLog = new SysLog(visitedTime,username,ip,url,executionTime,method);
sysLog.setId(UUID.randomUUID().toString());
mapper.insertLog(sysLog);
}
}