在了解spring aop中的關鍵字(如:連接點(JoinPoint)、切入點(PointCut)、切面(Aspact)、織入(Weaving)、通知(Advice)、目標(Target)等)后進行了簡單使用測試。
1.在spring的xml配置文件中添加代碼,開啟aop注解自動代理
<!-- 啟動aspectJ自動代理 --> <aop:aspectj-autoproxy />
2.創建一個方法作為連接點:
public class TestService { public void method1(){ System.out.println("執行method1"); } }
3.創建切面類(注解方式配置):
@Aspect// 注解該類為切面類 @Component public class LogIntercepter { // 若要以字符串形式表示執行目標條件必須使用final修飾 private final String EXEC = "execution(* com.lwl.service..*.*(..))"; // 執行順序:環繞通知(前),前置通知,環繞通知(后),后置通知,返回后通知 @Pointcut("execution(* com.lwl.service..*.*(..))")// 切入點 public void pointcutMethod(){}; @Before("pointcutMethod()")// 方法執行前執行 public void before(){ System.out.println("method before"); } @After("pointcutMethod()")// 方法執行后執行 public void after(){ System.out.println("method after"); } @AfterReturning("pointcutMethod()")// 方法返回后執行 public void afterReturning(){ System.out.println("method afterReturning"); } @AfterThrowing("pointcutMethod()")// 方法拋異常后執行 public void afterThrowing(){ System.out.println("method afterThrowing"); } @Around("pointcutMethod()")// 環繞通知 public void around(ProceedingJoinPoint pr){ System.out.println("method around bg"); try { pr.proceed();// 執行目標方法 } catch (Throwable e) { e.printStackTrace(); } System.out.println("method around ed"); } }
調用method1()后通知的打印先后順序結果為:
method around bg
method before
執行method1
method around ed
method after
method afterReturning
Spring AOP xml方式配置,在Spring的xml配置文件中加入(備忘):
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 1.注冊實體類(目標方法所在類) --> <bean id="userDao" class="com.huitong.Dao3.UserDao"></bean> <!-- 2.注冊AOP切面實體類(通知方法所在類) --> <bean id="aop" class="com.huitong.Dao3.Aop"></bean> <aop:config> <!-- 3.切入點配置 --> <aop:pointcut expression="execution(* com.huitong.Dao3.UserDao.*(..))" id="pt"/> <!-- 4.切面配置 --> <aop:aspect id="asp" ref="aop"> <!-- 5.通知配置 --> <aop:around method="around" pointcut-ref="pt"/> <aop:before method="before" pointcut-ref="pt"/> </aop:aspect> </aop:config>
AOP相關的術語:
-
通知: 通知定義了切面是什么以及何時使用的概念。Spring 切面可以應用5種類型的通知:
- 前置通知(Before):在目標方法被調用之前調用通知功能。
- 后置通知(After):在目標方法完成之后調用通知,此時不會關心方法的輸出是什么。
- 返回通知(After-returning):在目標方法成功執行之后調用通知。
- 異常通知(After-throwing):在目標方法拋出異常后調用通知。
- 環繞通知(Around):通知包裹了被通知的方法,在被通知的方法調用之前和調用之后執行自定義的行為。
-
連接點:是在應用執行過程中能夠插入切面的一個點。
- 切點: 切點定義了切面在何處要織入的一個或者多個連接點。
- 切面:是通知和切點的結合。通知和切點共同定義了切面的全部內容。
- 引入:引入允許我們向現有類添加新方法或屬性。
- 織入:是把切面應用到目標對象,並創建新的代理對象的過程。切面在指定的連接點被織入到目標對象中。在目標對象的生命周期中有多個點可以進行織入:
- 編譯期: 在目標類編譯時,切面被織入。這種方式需要特殊的編譯器。AspectJ的織入編譯器就是以這種方式織入切面的。
- 類加載期:切面在目標加載到JVM時被織入。這種方式需要特殊的類加載器(class loader)它可以在目標類被引入應用之前增強該目標類的字節碼。
- 運行期: 切面在應用運行到某個時刻時被織入。一般情況下,在織入切面時,AOP容器會為目標對象動態地創建一個代理對象。SpringAOP就是以這種方式織入切面的。