Spring Boot的AOP自定义注解,且解析参数

定义注解类:



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>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值