青岛谁家做网站,wordpress文章导入公众号,wordpress 企业主模板,成都诗和远方网站建设SpringAOP自定义注解实现日志功能
上篇文章讲解了springAOP实现简单日志功能#xff0c;这次讲解使用自定义注解实现日志功能。具体pom、Spring、SpringMVC的配置不再进行讲解#xff0c;详情点击链接查看[SpringAOP Aspect注解实现简单日志功能]。
如果你的项目使用的是sp…SpringAOP自定义注解实现日志功能
上篇文章讲解了springAOP实现简单日志功能这次讲解使用自定义注解实现日志功能。具体pom、Spring、SpringMVC的配置不再进行讲解详情点击链接查看[SpringAOP Aspect注解实现简单日志功能]。
如果你的项目使用的是springBoot的话直接在pom中引入SpringAOP的相关依赖即可
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-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.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;Component
Aspect
public 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自定义注解可以定义多个成员根据实际需求使用。