前言:在开发过程中,需要对每个方法执行时进行日志记录,故而整理一下有关AOP的相关知识点。
一、基本概念:
1、切面类 @Aspect: 定义切面类,加上@Aspect、@Component注解;//下文有展示
2、切点 @Pointcut:
// 指定切面方法
@Pointcut("execution(public * com.rest.module..*.*(..))")
public void getMethods() {
}
注:execution表达式第一个*表示匹配任意的方法返回值,..(两个点)表示零个或多个,第一个..表示module包及其子包,第二个*表示所有类, 第三个*表示所有方法,第二个..表示方法的任意参数个数
// 指定注解
@Pointcut("@annotation(com.rest.utils.SysPlatLog)")
public void withAnnotationMethods() {
}
注:在这里,自定义了一个注解类,方法加注解即可使用;
/**
* 系统平台日志记录
*/
public @interface SysPlatLog {
// 操作名称
String operateName() default "";
// 操作描述
String logNote() default "";
}
3、Advice,在切入点上执行的增强处理,主要有五个注解:
@Before 在切点方法之前执行
@After 在切点方法之后执行
@AfterReturning 切点方法返回后执行
@AfterThrowing 切点方法抛异常执行
@Around 属于环绕增强,能控制切点执行前,执行后
4、JoinPoint :方法中的参数JoinPoint为连接点对象,它可以获取当前切入的方法的参数、代理类等信息,因此可以记录一些信息,验证一些信息等;
5、使用&&、||、!、三种运算符来组合切点表达式,表示与或非的关系;
6、@annotation(annotationType) 匹配指定注解为切入点的方法;
7、//aop代理对象
Object aThis = joinPoint.getThis();
//被代理对象
Object target = joinPoint.getTarget();
8、调用切面注解:
@SysPlatLog(operateName = "查看详情",logNote = "查看详情")
@SneakyThrows
public Result getItem(@RequestParam(required = false) String bs){
}
二、代码展示:
1 package com.npc.rest.utils; 2 3 import com.npc.rest.common.properites.AppSupPlatProperties; 4 import com.sys.model.SysLog; 5 import lombok.extern.slf4j.Slf4j; 6 import org.aspectj.lang.JoinPoint; 7 import org.aspectj.lang.annotation.*; 8 import org.springframework.stereotype.Component; 9 import java.lang.reflect.Method; 10 import java.util.*; 11 12 @Aspect 13 @Slf4j 14 @Component 15 public class SysPlatLogAspect { 16 17 /** 18 * 指定切面 19 */ 20 @Pointcut("execution(public * com.rest.module..*.*(..))") 21 public void getMethods() { 22 } 23 /** 24 * 指定注解 25 */ 26 @Pointcut("@annotation(com.rest.utils.SysPlatLog)") 27 public void withAnnotationMethods() { 28 } 29 30 /*** 31 * 拦截控制层的操作日志 32 * @param joinPoint 33 * @return 34 * @throws Throwable 35 */ 36 @After(value = "getMethods() && withAnnotationMethods()") 37 public void recordLog(JoinPoint joinPoint) throws Throwable { 38 SysLog sysLog = new SysLog(); 39 SysPlatLog sysPlatLog = getInter(joinPoint); 40 sysLog.setOperateName(sysPlatLog.operateName()); 41 sysLog.setLogNote(sysPlatLog.logNote()); 42 sysLog.setLogTime(new Date()); 43 sysLog.setAppCode(AppSupPlatProperties.getAppCode()); 44 } 45 46 public SysPlatLog getInter(JoinPoint joinPoint) throws ClassNotFoundException { 47 String targetName = joinPoint.getTarget().getClass().getName(); 48 String methodName = joinPoint.getSignature().getName(); 49 Object[] arguments = joinPoint.getArgs(); 50 Class targetClass = Class.forName(targetName); 51 Method[] methods = targetClass.getMethods(); 52 for (Method method : methods) { 53 if (method.getName().equals(methodName)) { 54 Class[] clazzs = method.getParameterTypes(); 55 if (clazzs.length == arguments.length) { 56 SysPlatLog sysPlatLog = method.getAnnotation(SysPlatLog.class); 57 return sysPlatLog; 58 } 59 } 60 } 61 return null; 62 } 63 }