定义注解类:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AspectSysLog {
String record() default "";
}
注入类:
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
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.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.using.common.core.bean.ErrorEnum;
import com.using.common.core.exception.BusinessException;
import com.using.judge.auth.entity.extra.ExtraUsers;
import com.using.judge.web.client.common.entity.table.BusinessLog;
import com.using.judge.web.client.common.entity.vo.AspectSysLog;
import com.using.judge.web.client.mapper.BusinessLogMapper;
import com.using.judge.web.client.service.UserService;
import com.using.judge.web.client.utils.SnowflakeIdWorker;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
@Aspect
@Component
public class SysLogAspect {
final static Logger log = LoggerFactory.getLogger(SysLogAspect.class);
@Resource
private UserService userService;
@Autowired
private BusinessLogMapper businessLogMapper;
ThreadLocal<Long> beginTime = new ThreadLocal<>();
@Pointcut("@annotation(analysisActuator)")
public void serviceStatistics(AspectSysLog analysisActuator) {
}
@Before("serviceStatistics(analysisActuator)")
public void doBefore(JoinPoint joinPoint, AspectSysLog analysisActuator) {
// 记录请求到达时间
beginTime.set(System.currentTimeMillis());
log.info("cy666 note:{}", analysisActuator.record());
}
@After("serviceStatistics(analysisActuator)")
public void doAfter(JoinPoint joinPoint,AspectSysLog analysisActuator) throws ClassNotFoundException, NotFoundException, BusinessException {
//类名
String targetName = joinPoint.getTarget().getClass().getName();
//方法名
String methodName = joinPoint.getSignature().getName();
//参数
Object[] arguments = joinPoint.getArgs();
Class targetClass = Class.forName(targetName);
Method[] methods = targetClass.getMethods();
Map<String, Object> resultMap = getFieldsName(this.getClass(),targetClass.getName(),methodName,arguments);
log.info("cy666 statistic time:{}, note:{}", System.currentTimeMillis() - beginTime.get(), analysisActuator.record());
BusinessLog businessLog = new BusinessLog();
SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);
businessLog.setId(String.valueOf(snowflakeIdWorker.nextId()));
businessLog.setMethodName(targetClass.getName()+"."+methodName);
businessLog.setParameter(JSON.toJSONString(resultMap));
ExtraUsers currentUser = userService.findCurrentUser();
if (currentUser != null) {
businessLog.setOperationUser(currentUser.getName());
}else {
Map tmpMap = JSON.parseObject(JSON.toJSONString(resultMap.get("map")), Map.class);
businessLog.setOperationUser(tmpMap.containsKey("token")?tmpMap.get("token").toString():"");
}
businessLog.setMethodTime(System.currentTimeMillis()-beginTime.get());
businessLog.setOperationRecord(analysisActuator.record());
businessLogMapper.insertSelective(businessLog);
beginTime.set(System.currentTimeMillis());
}
private Map<String, Object> getFieldsName(Class cls, String clazzName, String methodName, Object[] args) throws NotFoundException {
Map<String, Object> map = new HashMap<String, Object>();
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(cls);
pool.insertClassPath(classPath);
CtClass cc = pool.get(clazzName);
CtMethod cm = cc.getDeclaredMethod(methodName);
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
}
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < cm.getParameterTypes().length; i++) {
map.put(attr.variableName(i + pos), args[i]);
}
return map;
}
}
使用:
@AspectSysLog(record = "查询学生详细信息")
@PostMapping(value="/testRequest")
public JsonResult<PageResult> testRequest(@RequestParam(value="userid",required=false) Integer userid){
return null;
}
使用maven的jar:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>