普通AOP開發(XML方式)
一、使用AOP目的
使用AOP的目的:就是對類裏面的方法進行增強
- 前置增強:在方法執行之前加入相關代碼
- 後置增強:在方法執行之後加入相關代碼
- 環繞增強:前置增強和後置增強
- 異常增強:在目標方法發生異常時加入相關代碼
二、AOP開發中的概念
- JoinPoint(連接點):所謂連接點是指哪些被攔截的點,而spring 中這些點就是指方法,因爲spring只支持方法類型的連接點。
- PointCut(切入點):所謂切入點就是指我們要對那些JoinPoint 進行攔截的定義。
- Advice(通知/增強):所謂通知/增強,就是指攔截到JoinPoint後需要完成的事情,它分爲前置通知/增強,後置通知/增強,異常通知/增強,最終通知/增強,環繞通知/增強(切面要完成的功能)
- Introduction(引介):引介是一種特殊的Advice,在不修改代碼的前提下,引介可以在運行期爲類動態的添加一些方法或Field。
- Target(目標):代理對象的目標對象(要增強的類)
- Weaving(織入):把 Advice 應用到 Target 的過程
- Proxy(代理):一個類被 AOP 注入增強後,就產生了一個結果代理類
- Aspect(切面):是 PointCut 和Advice(Introduction)的結合
三、示例
1. 創建項目並導包
2. 創建Person
3. 創建applicationContext.xml
<!-- 導入頭文件 -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
4. 前置通知
- 創建MyBeforeAdvise
- 配置applicationContext.xml
- 測試
5. 後置通知
- 創建MyAfterAdvise
- 配置applicationContext.xml
6. 環繞通知
- 第一種環繞通知
|-- 創建MyBeforeAdvise、MyAfterAdvise
|-- 配置applicationContext.xml
|-- 測試
- 第二種環繞通知
|-- 創建MyAroundAdvise
package com.lasing.advise;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
/**
* 環繞通知
* */
public class MyAroundAdvise implements MethodInterceptor{
/**
* MethodInvocation
* 目標方法執行對象
* */
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
before();
Object proceed = invocation.proceed();
after();
return proceed;
}
/**
* 執行前做的事
* */
public void before() {
System.out.println("飯前水果...");
}
/**
* 執行後做的事
* */
public void after() {
System.out.println("飯後甜點...");
}
}
|-- 配置applicationContext.xml
|-- 測試
7. 異常通知
- 手動設置一個異常
- 創建MyExceptionAdvise
- 配置applicationContext.xml
- 測試