Spring(十四):SpringAOP及AOP的三種實現方法

来源:https://www.cnblogs.com/jmsstudy/archive/2022/09/29/16740558.html
-Advertisement-
Play Games

一、什麼是AOP AOP為Aspect Oriented Programming的縮寫,意為:面向切麵編程,通過預編譯方式和運行期間動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的一個重要內容,是函數式編程的一種衍生範型。利用AOP可以 ...


一、什麼是AOP

AOP為Aspect Oriented Programming的縮寫,意為:面向切麵編程,通過預編譯方式和運行期間動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的一個重要內容,是函數式編程的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。

二、AOP的一些概念

1.Aspect(切麵):切麵是通知和切入點的結合。

2.Join point(連接點):與切入點匹配的執行點,例如執行方法或處理異常。在SpringAOP 中,連接點始終表示方法執行。

3.Advice(通知):在切麵中需要完成的工作。

4.Pointcut(切入點):切入通知執行的位置。

5.Target(目標):被通知的對象。

6. proxy(代理):向目標對象應用通知之後創建的對象。

7.Introduction(引入):向現有類添加新的方法或屬性。

8.Weaving(織入):將各個方面與其他應用程式類型或對象鏈接起來,以創建通知的對象。

三、AOP的三種實現方法

首先我們需要導入依賴:

     <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.9.1</version>
        </dependency>

1.通過SpringAPI介面進行實現

SpringAOP有五種通知方式,也有對應的介面:

Before:前置通知,在目標方法調用前通知,對應介面:MethodBeforeAdvice;

After:後置通知,在目標方法返回或異常後通知,對應介面:AfterReturningAdvice;

AfterReturning:後置返回通知,在目標方法返回後通知,對應介面:AfterReturningAdvice;

AfterThrowing:異常通知,在目標方法拋出異常後通知,對應介面:ThrowsAdvice;

Around:環繞通知:通知方法會將目標方法包裹起來,對應介面:MethodInterceptor;

我們下麵以具體的例子來展示:

(1)定義一個介面

package com.jms.service;

public interface UserService {
    void create();
    void read();
    void update();
    void delete();
}

(2)介面的實現類

package com.jms.service;

public class UserServiceImpl implements UserService{
    @Override
    public void create() {
        System.out.println("建立了一個用戶信息");
    }

    @Override
    public void read() {
        System.out.println("讀取了一個用戶信息");
    }

    @Override
    public void update() {
        System.out.println("更新了一個用戶信息");
    }

    @Override
    public void delete() {
        System.out.println("刪除了了一個用戶信息");
    }
}

(3)建立兩個類分別繼承前置通知和後置返回通知的介面

package com.jms.log;

import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;

public class beforeLog implements MethodBeforeAdvice {
    @Override
    //method:要執行目標對象的方法
    //args:參數
    //target:目標對象
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("[Debug]" + target.getClass().getName() + "的" + method.getName() + "執行...");
    }
}
package com.jms.log;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

public class afterLog implements AfterReturningAdvice{
    //returnValue:返回值
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("[Debug]" + target.getClass().getName() + "的" + method.getName() + "執行完成,返回了" + returnValue);
    }
}

(4)xml配置文件

註冊bean,並且配置aop

<?xml version="1.0" encoding="UTF-8"?>
<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/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="com.jms.service.UserServiceImpl"/>
    <bean id="beforeLog" class="com.jms.log.beforeLog"/>
    <bean id="afterLog" class="com.jms.log.afterLog"/>

    <!--方法一:使用SpringAPI介面-->
    <!--aop配置-->
    <aop:config>
        <!--pointcut:切入點
            expression:表達式
        -->
        <aop:pointcut id="pointcut" expression="execution(* com.jms.service.UserServiceImpl.*(..))"/>
        <!--執行環繞增加-->
        <aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>


</beans>

(5)測試

@Test
    public void test1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        /*
        UserServiceImpl userService = applicationContext.getBean("userService", UserServiceImpl.class)這樣執行會報錯
        因為動態代理代理的是介面,所以必須獲取介面
         */
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.create();
    }

測試結果如下:

 

 

 2.自定義類、自定義切麵實現

介面以及實現類都與上面相同

(1)自定義切麵類

package com.jms.diy;
public class diyAspect {

    public void before() {
        System.out.println("[Debug]方法執行...");
    }

    public void after() {
        System.out.println("[Debug]方法執行完成");
    }
}

切麵類中自定義通知方法

(2)xml配置文件

註入切麵類的Bean,配置AOP

<?xml version="1.0" encoding="UTF-8"?>
<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/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="userService" class="com.jms.service.UserServiceImpl"/>

    <!--方法二:自定義類,自定義切麵-->
    <bean id="diyAspect" class="com.jms.diy.diyAspect"/>
    <aop:config>
        <!--自定義切麵-->
        <aop:aspect ref="diyAspect">
            <!--切入點-->
            <aop:pointcut id="pointcut1" expression="execution(* com.jms.service.UserServiceImpl.*(..))"/>
            <aop:after method="after" pointcut-ref="pointcut1"/>
            <aop:before method="before" pointcut-ref="pointcut1"/>
        </aop:aspect>
    </aop:config>


</beans>

(3)測試如下

 

 3.通過註解實現

這種實現其實是第二種的註解方式

(1)自定義切麵類

package com.jms.diy;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class annotationAspect {
    @Before("execution(* com.jms.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("[Debug]方法前置增強");
    }

    @After("execution(* com.jms.service.UserServiceImpl.*(..))")
    public void after() {
        System.out.println("[Debug]方法後置增強");
    }
}

(2)此處還是採用xml配置,也可以採用java類配置

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="userService" class="com.jms.service.UserServiceImpl"/>

    <!--方法三:註解-->
    <!--增加註解支持-->
    <context:annotation-config/>
    <context:component-scan base-package="com.jms"/>
    <aop:aspectj-autoproxy/>
    
</beans>

(3)測試

 

(本文僅作個人學習記錄用,如有紕漏敬請指正)


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在學習之前,我們先瞭解一個網站mybatis-spring,這是mybatis-spring整合的官方文檔,裡面有詳細的教程,網址如下: https://mybatis.org/spring/zh/index.html 一、什麼是mybatis-spring 以下是mybatis-spring官方給 ...
  • 2022-09-29 問題描述: 在“setting.py”的配置文件中修改資料庫引擎中,將系統預設的"sqlite3"尾碼改為了“sql”。出現問題。 原因分析: 問題查看: 修改後: 上述問題修改後,在“setting”中設置資料庫的其他內容(主機、埠、用戶、密碼、使用的指定數據名的資料庫), ...
  • 在Word中創建報告時,我們經常會遇到這樣的情況:我們需要將數據從Excel中複製和粘貼到Word中,這樣讀者就可以直接在Word中瀏覽數據,而不用打開Excel文檔 ...
  • 近期在處理一個將NVR錄像機上的錄像下載到伺服器並通過瀏覽器播放的需求。 梳理記錄下過程,做個備忘,同時遇到的一些細節問題解決,也供需要的同學參考。 需求比較簡單,就是把指定時間段的錄像上傳到伺服器保存,並且允許用戶通過web頁面web瀏覽器,進行播放, 並且可以拖動控制播放進度。效果如。 一、 視 ...
  • Python常用的英語單詞就那麼幾個,多打就熟悉了 說來好笑,我壓根就沒記英語單詞… 真的就是純靠多打多練, 畢竟打多了之後肌肉記憶就在那裡了 下麵就給大家帶來常用python清單彙總~ 一、互動式環境與print輸出(https://jq.qq.com/?_wv=1027&k=2Q3YTfym) ...
  • 一、線程的概念線程是CPU分配資源的基本單位。當一程式開始運行,這個程式就變成了一個進程,而一個進程相當於一個或者多個線程。當沒有多線程編程時,一個進程相當於一個主線程;當有多線程編程時,一個進程包含多個線程(含主線程)。使用線程可以實現程式大的開發。 多個線程可以在同一個程式中運行,並且每一個線程 ...
  • 一、整型數據類型 1、整型數據類型名稱及關鍵詞 2、為什麼要定義不同的整型類型? 因為不同的數據類型所占用的記憶體大小是不同的,他們可表示的數據範圍也是不同的。那麼char,short,int,long,long long,分別占用幾個位元組?具體的數值範圍又是多少?C語言並未規定數據類型的大小範圍,具 ...
  • 在上一篇文章`《驅動開發:內核字元串轉換方法》`中簡單介紹了內核是如何使用字元串以及字元串之間的轉換方法,本章將繼續探索字元串的拷貝與比較,與應用層不同內核字元串拷貝與比較也需要使用內核專用的API函數,字元串的拷貝往往伴隨有內核記憶體分配,我們將首先簡單介紹內核如何分配堆空間,然後再以此為契機簡介字... ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...