栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Aop之AspectJ注解配置实现日志管理的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Aop之AspectJ注解配置实现日志管理的方法

最近项目要做一个日志功能,我用Spring Aop的注解方式来实现。

创建日志注解

package com.wyj.annotation;

import java.lang.annotation.documented;
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)
@documented
public @interface SysLog {

 String action() default "";//动作

}

创建切面通知类

记录操作的方法名,参数和花费的时间,使用环绕通知

package com.wyj.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wyj.annotation.SysLog;
import com.wyj.entity.SysLogEntity;
import com.wyj.service.SysLogService;


@Aspect
@Component
public class SysLogAspect {

 @Autowired
 private SysLogService sysLogService;

 
 @Pointcut("@annotation(com.wyj.annotation.SysLog)")
 public void pointCut() {}

 
 @Around("pointCut()")
 public Object aroud(ProceedingJoinPoint joinPoint) throws Throwable {

  // 开始时间
  long beginTime = System.currentTimeMillis();

  // 执行目标方法
  Object result = joinPoint.proceed();

  // 执行时长(毫秒)
  long time = System.currentTimeMillis() - beginTime;

  // 保存日志
  saveSysLog(joinPoint, time);
  return result;
 }

 
 private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
  MethodSignature signature = (MethodSignature) joinPoint.getSignature();
  Method method = signature.getMethod();
  SysLogEntity sysLogEntity = new SysLogEntity();
  SysLog sysLog = method.getAnnotation(SysLog.class);
  if (sysLog != null) {

   // 注解上的描述
   sysLogEntity.setOperation(sysLog.action());
  }

  // 获取目标类名
  String className = joinPoint.getTarget().getClass().getName();

  // 获取方法名
  String methodName = signature.getName();
  sysLogEntity.setMethod(className + "." + methodName + "()");

  // 请求的参数
  Object[] args = joinPoint.getArgs();
  if (args != null && args.length != 0 && args[0] != null) {
   sysLogEntity.setParams(args[0].toString());
  }
  sysLogEntity.setTime(time);

  // 保存系统日志
  sysLogService.save(sysLogEntity);
 }
}

扫描和启动aop注解

日志注解的应用

效果

以上这篇Spring Aop之AspectJ注解配置实现日志管理的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/141963.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号