Spring普通AOP開發(XML方式)

一、使用AOP目的

使用AOP的目的:就是對類裏面的方法進行增強

  • 前置增強:在方法執行之前加入相關代碼
  • 後置增強:在方法執行之後加入相關代碼
  • 環繞增強:前置增強和後置增強
  • 異常增強:在目標方法發生異常時加入相關代碼

二、AOP開發中的概念

  1. JoinPoint(連接點):所謂連接點是指哪些被攔截的點,而spring 中這些點就是指方法,因爲spring只支持方法類型的連接點。
  2. PointCut(切入點):所謂切入點就是指我們要對那些JoinPoint 進行攔截的定義。
  3. Advice(通知/增強):所謂通知/增強,就是指攔截到JoinPoint後需要完成的事情,它分爲前置通知/增強,後置通知/增強,異常通知/增強,最終通知/增強,環繞通知/增強(切面要完成的功能)
  4. Introduction(引介):引介是一種特殊的Advice,在不修改代碼的前提下,引介可以在運行期爲類動態的添加一些方法或Field。
  5. Target(目標):代理對象的目標對象(要增強的類)
  6. Weaving(織入):把 Advice 應用到 Target 的過程
  7. Proxy(代理):一個類被 AOP 注入增強後,就產生了一個結果代理類
  8. 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. 環繞通知

  1. 第一種環繞通知
     |-- 創建MyBeforeAdvise、MyAfterAdvise
    在這裏插入圖片描述
    在這裏插入圖片描述
     |-- 配置applicationContext.xml
    在這裏插入圖片描述
     |-- 測試
    在這裏插入圖片描述
  2. 第二種環繞通知
     |-- 創建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
    在這裏插入圖片描述
  • 測試
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章