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
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...