1.引入aop依赖
<!-- aop依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
2.开启包扫描
<context:component-scan base-package="cn.kgc.spring"></context:component-scan>
3.使用aop开启注解
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4.创建切面类使用注解
package cn.kgc.spring.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/*
@author peng
@date4/7/2022
切面类: 可以添加各种类型的通知
*/
@Component
@Aspect //标记当前类时通知类
public class AllAdvice {
//实现切点表达式的复用
@Pointcut("execution(* *(..))")
public void all(){
}
//前置通知
@Before("all()")
public void before() {
System.out.println("---前置通知---");
}
//后置通知
@AfterReturning("execution(* *(..))")
public void afterReturning() {
System.out.println("-------------后置通知---------------");
}
//最终通知 不管核心业务是否有异常 均要执行
@After(("execution(* *(..))"))
public void after() {
System.out.println("-------------最终通知---------------");
}
//异常通知 核心业务出现异常时添加的通知 没有异常不添加
@AfterThrowing(("execution(* *(..))"))
public void afterThrowing() {
System.out.println("---异常通知---");
}
//环绕通知
@Around(("execution(* *(..))"))
public Object around(ProceedingJoinPoint proceedingJoinPoint) {
try {
System.out.println("---环绕前置通知---");
Object proceed = proceedingJoinPoint.proceed();
System.out.println("---环绕后置通知---");
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("---环绕异常通知---");
} finally {
System.out.println("---环绕最终通知---");
}
return null;
}
}
5.运行结果