1.導入maven依賴
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.定義切面類
可以指定pointcut()再搭配@before等註解使用,也可以直接使用@before完成,具體參考下面兩個方法。
@Aspect
@Component
public class StuAspect {
//日誌打印
private static Logger log = Logger.getLogger(StuAspect.class.getClass());
//對controller包下的Demo類中hello函數進行增強
@Pointcut("execution(* learning01.controller.Demo.hello(..))")
public void pointcut(){}
@Before("pointcut()")
public void before(){
log.info("this is before");
//doSomething
}
@Before("execution(* learning01.controller.Demo.hello(..))")
public void defore2(){
//doSomething;
}
}
-
其他註解@after @AfterThrowing @AfterReturning等等 和上面類同
-
有參數情況下獲取函數參數或者函數返回參數aop如何實現呢
被切入的方法沒有參數的時候,可以使用上例中的那些簡單方式。
不過當被切入(或者說被通知)的方法存在參數時,我們想要在通知中獲取到該參數,就使用下面的方式。
@Component
public class Person {
public void say(String msg){
System.out.println(msg);
}
}
切面類
@Aspect
@Component
public class TestAspect {
@Before("execution(* learning01.bean.Person.say(String))&&args(message)")
public void beforeSay(String message){
System.out.println("執行say之前執行,獲取到參數爲"+message);
}
}
輸入hello aop
輸出結果
- 獲取目標函數返回結果再增強跟上面類同。
定義切入點表達式 execution(* com.sample.service.impl….(…))
execution()是最常用的切點函數,其語法如下所示:
整個表達式可以分爲五個部分:
- 1、execution(): 表達式主體。
- 2、第一個*號:表示返回類型,*號表示所有的類型。
- 3、包名:表示需要攔截的包名,後面的兩個句點表示當前包和當前包的 所有子包,com.sample.service.impl包、子孫包下所有類的方法。
- 4、第二個*號:表示類名,*號表示所有的類。
- 5、*(…):最後這個星號表示方法名,*號表示所有的方法,後面括弧裏面表示方法的參數,兩個句點表示任何參數。