spring 自定义用户操作apo切面注解

步骤一:创建注解格式

/**
 * 自定义日志操作注解
 * Target 说明了Annotation所修饰的对象范围
 * ElementType:
 * 1、CONSTRUCTOR:用于描述构造器
 * 2、FIELD:用于描述符
 * 3、LOCAL_VARIABLE:用于描述局部变量
 * 4、METHOD:用于描述方法
 * 5、PACKAGE:用于描述包
 * 6、PARAMETER: 用于描述参数
 * 7、TYPE: 用于描述类、接口(包括注解类型)或者enum声明
 * <p>
 * Retention 定义了该Annotation被保留的时间长短
 * RetentionPoicy:
 * 1、SOURCE:在源文件中有效(即源文件保留)
 * 2、CLASS:在class文件中有效(即class保留)
 * 3、RUNTIME:在运行时有效(即运行时保留)
 * <p>
 * Documented  用于描述其它类型的annotation应该被作为被标注的程序成员的公共API
 *
 * @author weirdo_world
 */
@Target(ElementType.METHOD)//注解放置的目标位置即方法级别
@Retention(RetentionPolicy.RUNTIME)//注解在哪个阶段执行
@Documented
public @interface MyOperationLog {
    /**
     * 操作描述
     */
    String desc() default "";
}

步骤二:创建切面日志处理类

/**
 * 日志记录 切面处理类
 *
 * @author weirdo_world
 */
@Aspect
@Component
public class SysLogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut(value = "@annotation(com.weirdo.aop.MyOperationLog)")
    public void pointcut() {
    }

    @AfterReturning("pointcut()")
    public void saveLog(JoinPoint joinPoint) {
        logger.info("进入切面日志");
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        HttpSession session = request.getSession();
        SessionUser user = SessionManager.getSessionUser(session.getId());
        AdminLog adminLog = new AdminLog();
        JSONObject jsonObject = new JSONObject();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            //获取操作
            MyOperationLog annotation = method.getAnnotation(MyOperationLog.class);
            if (annotation != null) {
                Object arg = joinPoint.getArgs()[0];
                Object json = JSON.toJSON(arg);
                boolean b = JsonUtil.isJsonObject(json.toString());
                if (b) {
                    jsonObject = JSONObject.parseObject(json.toString());
                }
                jsonObject.put("desc", annotation.desc());
                logger.info("操作说明:{}", annotation.desc());
            }
            if (user != null) {
                adminLog.setAdminid(user.getId());
                adminLog.setAdminname(user.getName());
                logger.info("用户信息:{},{}", user.getId(), user.getName());
            }
            String ipAddress = request.getRemoteAddr();
            jsonObject.put("url", request.getRequestURI());
            jsonObject.put("ipAddr", ipAddress);
            adminLog.setIp(ipAddress);
            adminLog.setContent(jsonObject.toJSONString());
            logger.info("保存数据:{},{}", adminLog, JSONObject.toJSONString(request.getParameterMap()));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("切面日志错误!{},json对象数据{}", e.getMessage(), jsonObject);
        }
    }
}

步骤三:使用

// 方法上加入下面注解即可
@MyOperationLog(desc = "操作新增用户")

如果需要增加参数或修改参数就需要用到下面的方法了

@Around("pointcut()")
    public Object doBefore(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String json = memCachedClient.get(request.getParameter("userId")).toString();
            Employee user = JSON.parseObject(json, Employee.class);
            JSONObject jsonObject;
            if (user != null) {
                Object[] args = joinPoint.getArgs();
                Object arg = args[0];
                boolean b = JsonUtil.isJsonObject(arg.toString());
                if (b) {
                    jsonObject = JSONObject.parseObject(arg.toString());
                    jsonObject.put("userName", user.getName());
                    jsonObject.put("userId", user.getId());
                    args[0] = jsonObject;
                    return joinPoint.proceed(args);
                }
            }
        }
        return joinPoint.proceed();
    }

猜你喜欢

转载自blog.csdn.net/weirdo_world/article/details/118756683