aop+自定义注解实现最近操作人

使用:
在service层添加注解,传入参数对象中必须包含aop逻辑中所需要的ProjectId
service层添加注解,传入参数对象中必须包含aop逻辑中所需要的ProjectId
自定义注解

import java.lang.annotation.*;

/**
 * 根据项目id修改当前操作人
 * 传参:如果被注解的方法中使用id来存项目Id则传入false
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UpdateRecentUser {
    //参数用来判断传入对象中是使用projectId还是id,如果是id则需要传入false
    boolean isProjectId() default true;
}

aop代码

import com.vivo.common.annotation.UpdateRecentUser;
import com.vivo.common.utils.GetSsoUserUtil;
import com.vivo.impl.SecurityProjectImpl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class HttpRequestAspect {

    private static final Logger log = LoggerFactory.getLogger(HttpRequestAspect.class);

    @Autowired
    private SecurityProjectImpl securityProjectImpl;

    public static long startTime;
    public static long endTime;

    /**
     * @Before注解表示在具体的方法之前执行
     */
    @Before("com.vivo.common.point.CommonJoinPointConfig.updateRecentUserPoint()")
    public void before(JoinPoint joinPoint) {
        startTime = System.currentTimeMillis();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取注解对象(目的是为了得到注解传入参数)
        UpdateRecentUser updateRecentUser = ((MethodSignature)joinPoint.getSignature()).getMethod().getAnnotation(UpdateRecentUser.class);
        Integer projectId = getJoinpointProjectId(joinPoint, updateRecentUser.isProjectId());
        //根据项目id修改当前操作用户
        securityProjectImpl.updateProjectRecentUser(projectId, GetSsoUserUtil.getCurrentUserName(request));
    }

    /**
     * 获取传入参数中的项目ID
     *
     * @param joinPoint
     * @return
     */
    private Integer getJoinpointProjectId(JoinPoint joinPoint, boolean isProjectId) {
        Object[] args = joinPoint.getArgs();
        Integer projectId = null;
        for (int i = 0; i < args.length; i++) {
            Object test = args[i];
            Map<String, Object> stringObjectMap = objectToMap(test);
            if (isProjectId) {
                projectId = Integer.parseInt(stringObjectMap.get("projectId").toString());
            } else {
                projectId = Integer.parseInt(stringObjectMap.get("id").toString());
            }
        }
        return projectId;
    }

    /**
     * @After 注解表示在方法执行之后执行
     */
    @After("com.vivo.common.point.CommonJoinPointConfig.updateRecentUserPoint()")
    public void after() {
        endTime = System.currentTimeMillis() - startTime;
    }

    /**
     * @AfterReturning 注解用于获取方法的返回值
     */
    @AfterReturning(pointcut = "com.vivo.common.point.CommonJoinPointConfig.updateRecentUserPoint()", returning = "object")
    public void getAfterReturn(Object object) {
        log.info("本次接口耗时={}ms", endTime);
        log.info("afterReturning={}", object == null ? null : object.toString());
    }

    /**
     * object转map
     *
     * @param obj
     * @return
     */
    public static Map<String, Object> objectToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            map.put(fieldName, value);
        }
        return map;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值