100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > SpringAOP+自定义注解实现日志功能

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

时间:2020-05-18 02:21:16

相关推荐

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

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

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

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

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

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

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 MethodInfo {String info() default "";}

Controller中的使用:

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

创建切面类LogAspect:

import java.lang.reflect.Method;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpSession;import org.aspectj.lang.JoinPoint;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.ponent;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;@Component@Aspectpublic class LogAspect {/*** 切入点,使用方法切点函数@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)")public void logPointcut(){}/*** 后置通知,JointPoint执行完成后执行,不论是否JointPoint异常,实质是finally中的代码块* @param joinPoint*/@After("logPointcut()")public void doAfter(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,自定义注解可以定义多个成员,根据实际需求使用。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。