spring aop使用,spring aop註解,Spring切麵編程

来源:https://www.cnblogs.com/fanshuyao/archive/2020/01/21/12220945.html
-Advertisement-
Play Games

©Copyright 蕃薯耀 2020-01-21 https://www.cnblogs.com/fanshuyao/ 一、第一步,引用依賴類,在Pom.xml加入依賴 <dependencies> <dependency> <groupId>org.springframework</groupI ...


================================

©Copyright 蕃薯耀 2020-01-21

https://www.cnblogs.com/fanshuyao/

 

一、第一步,引用依賴類,在Pom.xml加入依賴

<dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.12.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.12.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.12.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

 

二、第二步:增加配置類

1、@Configuration:聲明該類為配置類

2、@ComponentScan("com.lqy.spring.aop"):掃描相應的類,納入spring容器中管理

3、@EnableAspectJAutoProxy:啟用註解方式的Aop模式

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.lqy.spring.aop")
@EnableAspectJAutoProxy
public class AopConfig {

    
}

 

三、第三步:自定義邏輯運算

import org.springframework.stereotype.Component;

/**
 * Calculator類需要在spring容器才能使用aop
 * 使用:@Component,同時使用@ComponentScan註解掃描時,要掃描到該類
 *
 */
@Component
public class Calculator {

    public int divInteger(int a, int b) {
        System.out.println("除法運算");
        return a/b;
    }
    
    public double div(double a, double b) {
        System.out.println("除法運算");
        return a/b;
    }
    
    public double add(double a, double b) {
        System.out.println("加法運算");
        return a + b;
    }
}

 

四、第四步:運算邏輯類切麵註入類

1、@Before:方法執行之前

2、@After:方法執行之後(不管會不會出現異常都會執行)

3、@AfterReturning:方法正常執行返回之後

4、@AfterThrowing:方法發生異常執行

 

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 類需要在spring容器才能使用aop,並且添加切麵類的註解:@Aspect
 *
 */
@Aspect
@Component
public class CalculatorAop {
    

    /**
     * 公共切點
     */
    @Pointcut("execution( * com.lqy.spring.aop.Calculator.*(..))")
    public void pointCut() {}
    
    /**
     * 方法執行之前
     */
    @Before(value = "execution( * com.lqy.spring.aop.Calculator.*(..))")
    public void before(JoinPoint joinPoint) {
        System.out.println("");
        System.out.println("===============================================================");
        System.out.println("before方法:{" + joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName() + "}開始執行:");
        System.out.println("方法參數是:{" + Arrays.asList(joinPoint.getArgs()) + "}");
        
    }
    
    
    /**
     * 方法執行之後(不管會不會出現異常都會執行)
     * pointCut():使用公共的切點表達式
     */
    @After("pointCut()")
    public void after(JoinPoint joinPoint) {
        System.out.println("after方法:{" + joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName() + "}執行結束。");
    }
    
    /**
     * 方法正常執行返回之後
     */
    @AfterReturning(value = "pointCut()", returning = "returnResult")
    public void afterReturn(JoinPoint joinPoint, Object returnResult) {
        System.out.println("afterReturn方法:{" + joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName() + "}執行返回的結果是:{" + returnResult + "}。");
        System.out.println("");
    }
    
    /**
     * 方法出現異常執行
     */
    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
        System.out.println("afterThrowing方法:{" + joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName() + "}發生異常:" + ex);
    }

}

 

五、第五步:測試

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.lqy.spring.aop.Calculator;
import com.lqy.spring.config.AopConfig;

public class TestAop {

    private AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AopConfig.class);
    
    @Test
    public void testDiv() {
        Calculator cal = ac.getBean(Calculator.class);//Calculator類需要在spring容器才能使用aop
        //System.out.println(cal.div(3, 0));
        System.out.println(cal.add(3, 2));
        System.out.println(cal.divInteger(3, 0));
    }
    
}

 

 

 

測試結果

===============================================================
before方法:{com.lqy.spring.aop.Calculator.add}開始執行:
方法參數是:{[3.0, 2.0]}
加法運算
after方法:{com.lqy.spring.aop.Calculator.add}執行結束。
afterReturn方法:{com.lqy.spring.aop.Calculator.add}執行返回的結果是:{5.0}。

5.0

===============================================================
before方法:{com.lqy.spring.aop.Calculator.divInteger}開始執行:
方法參數是:{[3, 0]}
除法運算
after方法:{com.lqy.spring.aop.Calculator.divInteger}執行結束。
afterThrowing方法:{com.lqy.spring.aop.Calculator.divInteger}發生異常:java.lang.ArithmeticException: / by zero

 

 

(如果你覺得文章對你有幫助,歡迎捐贈,^_^,謝謝!) 

================================

©Copyright 蕃薯耀 2020-01-21

https://www.cnblogs.com/fanshuyao/


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

-Advertisement-
Play Games
更多相關文章
  • GC日誌 Heap PSYoungGen total 305664K, used 26214K [0x00000000eab00000, 0x0000000100000000, 0x0000000100000000) eden space 262144K, 10% used [0x00000000e ...
  • 報錯信息: qly@qlyComputer:~$ pip Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> from pip import main ImportError: cannot impo ...
  • 原文地址: "http://www.work100.net/training/java" 更多教程: "光束雲 免費課程" Java入門 Java 是由 Sun Microsystems 公司於1995年5月推出的高級程式設計語言。 Java 可運行於多個平臺,如 、`Mac OS UNIX`版本的 ...
  • 需要源碼、JDK1.6 、編碼風格參考阿裡java規約 7/12開始 有點意識到自己喜歡理論大而泛的模糊知識的學習,而不喜歡實踐和細節的打磨,是因為粗心浮躁導致的麽? cron表達式使用 設計能力、領域建模能力 其他: 海明威的硬幣:老人與海 工具準備: java編程思想電子版 別人整理的思維導圖 ...
  • 在IntelliJ Idea中HTML格式化時,預設head和body標簽以及body下的標簽都不會縮進,這就導致你每次寫好html時候格式化的時候所有標簽都是同一層級沒有縮進,一般我們寫html都會層級關係標簽嵌套,通過縮進看代碼結構就很清晰明朗 ...
  • 1.什麼是二維碼? ​ (百度百科):二維碼又稱二維條碼,常見的二維碼為QR Code,QR全稱Quick Response,是一個近幾年來移動設備上超流行的一種編碼方式,它比傳統的Bar Code條形碼能存更多的信息,也能表示更多的數據類型。 2.利用ZXING生成二維碼 ​ ·對應POM <de ...
  • 近期項目用到了緩存,我選用的是主流的google.guava作本地緩存,redis作分散式 緩存,先說說我對本地緩存和分散式緩存的理解吧,可能不太成熟的地方,大家指出,一起 學習.本地緩存的特點是速度快,不會受到網路阻塞的干擾,但由於是放在本地記憶體中,所 以容量較小,不能項目間共用比IO效率高比re ...
  • a.php <?phpheader("Content-type: text/html; charset=utf-8");date_default_timezone_set("Asia/Shanghai"); $start = microtime(true); function fsockopen_g ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...