SpringAOP+自定义注解实现日志功能

2022-10-30 10:17:59

SpringAOP+自定义注解实现日志功能

上篇文章讲解了springAOP实现简单日志功能,这次讲解使用自定义注解实现日志功能。具体pom、Spring、SpringMVC的配置不再进行讲解,详情点击链接查看[SpringAOP Aspect注解实现简单日志功能]

如果你的项目使用的是springBoot的话,直接在pom中引入SpringAOP的相关依赖即可:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>

完成相关配置后,首先创建一个自定义注解类MethodInfo:

importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public@interfaceMethodInfo{Stringinfo()default"";}

Controller中的使用:

@RequestMapping(value="test")@MethodInfo(info="测试管理")publicStringlist(){System.out.println("这是一个joinPoint");return"xxx";}

创建切面类LogAspect:

importjava.lang.reflect.Method;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Pointcut;importorg.aspectj.lang.reflect.MethodSignature;importorg.springframework.stereotype.Component;importorg.springframework.web.context.request.RequestContextHolder;importorg.springframework.web.context.request.ServletRequestAttributes;@Component@AspectpublicclassLogAspect{/**
	 * 切入点,使用方法切点函数@annotation匹配
	 * @annotation(com.xx.xx.MethodInfo):表示标注了特定注解MethodInfo的JointPoint
	 * 如果想特定某些包下使用MethodInfo注解的JointPoint可以结合使用
	 * execution(* com.xx.xx..*(..))&& @annotation(com.xx.xx.MethodInfo)
	 */@Pointcut("@annotation(com.xx.xx.MethodInfo)")publicvoidlogPointcut(){}/**
	 * 后置通知,JointPoint执行完成后执行,不论是否JointPoint异常,实质是finally中的代码块
	 * @param joinPoint
	 */@After("logPointcut()")publicvoiddoAfter(JoinPoint joinPoint){MethodSignature ms=(MethodSignature)joinPoint.getSignature();/**
		 * 此处不使用((MethodSignature)joinPoint.getSignature()).getMethod()获取Method,
		 * 因为如果方法是接口的实现获取到的将是该方法接口
		 */Method method= joinPoint.getTarget().getClass().getDeclaredMethod(ms.getName(), ms.getParameterTypes());MethodInfo mi= method.getAnnotation(MethodInfo.class);//获取自定义注解对象String info= mi.info();//获取注解成员信息,例如@MethodInfo(info="测试管理")获取到的就是测试管理HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();String ip= request.getRemoteAddr();// 获取IP地址HttpSession session= request.getSession();//获取sessionUser user=(User)session.getAttribute("userCache");//从session中获取当前用户信息,根据自身项目实际情况而定//保存日志操作System.out.println("执行保存日志操作...");}}

以上我们就简单实现了使用自定义注解方式的aop,自定义注解可以定义多个成员,根据实际需求使用。

  • 作者:Archie_java
  • 原文链接:https://lebron.blog.csdn.net/article/details/121844239
    更新时间:2022-10-30 10:17:59