个人Blog:链接地址
AOP
① 引入依赖
<!-- aop-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
② 开启aop
aop:#true使用cqlib动态代理
proxy-target-class:true#是否开启aop
auto: true
③ 注解切入点
package com.sangeng.aop;
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 InvokeLog {
}
④ 配置切面类
package com.sangeng.aop;
import org.aspectj.lang.JoinPoint;
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.stereotype.Component;
import java.util.Arrays;
@Aspect //标识这是一个切面类
@Component
public class InvokeLogAspect {
//确定切点
@Pointcut("@annotation(com.sangeng.aop.InvokeLog)")
public void pt() {
}
@Around("pt()")
public Object printInvokeLog(ProceedingJoinPoint joinPoint) {
//目标方法调用前
Object proceed = null;
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
//类名
String className = signature.getDeclaringTypeName();
//方法名
String methodName1 = signature.getName();
//调用时传入的参数
Object[] args = joinPoint.getArgs();
//被代理对象
Object target = joinPoint.getTarget();
System.out.println(className+"=="+methodName1+"======"+ Arrays.toString(args));
System.out.println(methodName + "即将被调用");
try {
proceed = joinPoint.proceed();
//目标方法调用后
System.out.println(methodName + "被调用完了");
} catch (Throwable throwable) {
throwable.printStackTrace();
//目标方法出现异常了
System.out.println(methodName + "出现了异常");
}
return proceed;
}
}