## 第一步 開啟aop支持
~~~
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("cn.maicaii.*")
/**
* 目標對象實現了接口 – 使用CGLIB代理機制
* 目標對象沒有接口(只有實現類) – 使用CGLIB代理機制
* false
* 目標對象實現了接口 – 使用JDK動態代理機制(代理所有實現了的接口)
* 目標對象沒有接口(只有實現類) – 使用CGLIB代理機制
*/
@EnableAspectJAutoProxy(proxyTargetClass = true) // 第一步 開啟aop
public class Config {
}
~~~
## 第二部 導入apo jar包
~~~
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
~~~
## 第三步 編寫切面類
~~~
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 切面類
*/
@Component
@Aspect // 需要導入 aspectjweaver 包
public class UserAspect {
/**
* 切點
*/
@Pointcut("execution(* cn.maicaii.service.*.*(..))")
public void pointcut() {
}
/**
* 執行之前
*/
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
System.out.println("執行方法之前執行");
}
/**
* 當匹配的方法執行 正常 返回時運行。 在 After 之后
*/
@AfterReturning(pointcut = "pointcut()", returning = "retVal")
public void afterReturning(Object retVal) {
System.out.println(retVal);
System.out.println("執行方法正常 返回時運行時 執行");
}
/**
* 執行之后
*/
@After("pointcut()")
public void after() {
System.out.println("執行方法之后執行");
}
/**
* 當匹配的方法執行通過拋出異常退出時,拋出通知運行后。您可以使用@AfterThrowing注解來聲明它
*/
@AfterThrowing("pointcut()")
public void afterThrowing(){
System.out.println("執行方法時有異常時執行");
}
/**
* 環繞通知
*/
@Around("pointcut()")
public void around(ProceedingJoinPoint point) throws Throwable {
System.out.println("環繞通知之前");
point.proceed();
System.out.println("環繞通知之后");
}
}
~~~