国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

spring之面向切面:AOP(2)

這篇具有很好參考價值的文章主要介紹了spring之面向切面:AOP(2)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

學習的最大理由是想擺脫平庸,早一天就多一份人生的精彩;遲一天就多一天平庸的困擾。各位小伙伴,如果您:
想系統(tǒng)/深入學習某技術知識點…
一個人摸索學習很難堅持,想組團高效學習…
想寫博客但無從下手,急需寫作干貨注入能量…
熱愛寫作,愿意讓自己成為更好的人…


前言

一、基于注解的AOP
1、技術說明
2、準備工作
3、創(chuàng)建切面類并配置
4、各種通知
5、切入點表達式語法
6、重用切入點表達式
7、獲取通知的相關信息
8、環(huán)繞通知
9、切面的優(yōu)先級
二、基于XML的AOP
1、準備工作
2、實現(xiàn)


一、基于注解的AOP

1、技術說明

spring之面向切面:AOP(2),Spring&SpringMVC,spring,java,后端
spring之面向切面:AOP(2),Spring&SpringMVC,spring,java,后端

  • 動態(tài)代理分為JDK動態(tài)代理和cglib動態(tài)代理
  • 當目標類有接口的情況使用JDK動態(tài)代理和cglib動態(tài)代理,沒有接口時只能使用cglib動態(tài)代理
  • JDK動態(tài)代理動態(tài)生成的代理類會在com.sun.proxy包下,類名為$proxy1,和目標類實現(xiàn)相同的接口
  • cglib動態(tài)代理動態(tài)生成的代理類會和目標在在相同的包下,會繼承目標類
  • 動態(tài)代理(InvocationHandler):JDK原生的實現(xiàn)方式,需要被代理的目標類必須實現(xiàn)接口。因為這個技術要求代理對象和目標對象實現(xiàn)同樣的接口(兄弟兩個拜把子模式)。
  • cglib:通過繼承被代理的目標類(認干爹模式)實現(xiàn)代理,所以不需要目標類實現(xiàn)接口。
  • AspectJ:是AOP思想的一種實現(xiàn)。本質上是靜態(tài)代理,將代理邏輯“織入”被代理的目標類編譯得到的字節(jié)碼文件,所以最終效果是動態(tài)的。weaver就是織入器。Spring只是借用了AspectJ中的注解。

2、準備工作

①添加依賴

在IOC所需依賴基礎上再加入下面依賴即可:

<dependencies>
    <!--spring context依賴-->
    <!--當你引入Spring Context依賴之后,表示將Spring的基礎依賴引入了-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.2</version>
    </dependency>

    <!--spring aop依賴-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>6.0.2</version>
    </dependency>
    <!--spring aspects依賴-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>6.0.2</version>
    </dependency>

    <!--junit5測試-->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!--log4j2的依賴-->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.19.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j2-impl</artifactId>
        <version>2.19.0</version>
    </dependency>
</dependencies>

②準備被代理的目標資源

接口:

public interface Calculator {
    
    int add(int i, int j);
    
    int sub(int i, int j);
    
    int mul(int i, int j);
    
    int div(int i, int j);
    
}

實現(xiàn)類:

@Component
public class CalculatorImpl implements Calculator {
    
    @Override
    public int add(int i, int j) {
    
        int result = i + j;
    
        System.out.println("方法內部 result = " + result);
    
        return result;
    }
    
    @Override
    public int sub(int i, int j) {
    
        int result = i - j;
    
        System.out.println("方法內部 result = " + result);
    
        return result;
    }
    
    @Override
    public int mul(int i, int j) {
    
        int result = i * j;
    
        System.out.println("方法內部 result = " + result);
    
        return result;
    }
    
    @Override
    public int div(int i, int j) {
    
        int result = i / j;
    
        System.out.println("方法內部 result = " + result);
    
        return result;
    }
}

3、創(chuàng)建切面類并配置

// @Aspect表示這個類是一個切面類
@Aspect
// @Component注解保證這個切面類能夠放入IOC容器
@Component
public class LogAspect {
    
    @Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
    }

    @After("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->后置通知,方法名:"+methodName);
    }

    @AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->返回通知,方法名:"+methodName+",結果:"+result);
    }

    @AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->異常通知,方法名:"+methodName+",異常:"+ex);
    }
    
    @Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行之前");
            //目標對象(連接點)方法的執(zhí)行
            result = joinPoint.proceed();
            System.out.println("環(huán)繞通知-->目標對象方法返回值之后");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("環(huán)繞通知-->目標對象方法出現(xiàn)異常時");
        } finally {
            System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行完畢");
        }
        return result;
    }
    
}

在Spring的配置文件中配置:

<?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:context="http://www.springframework.org/schema/context"
       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">
    <!--
        基于注解的AOP的實現(xiàn):
        1、將目標對象和切面交給IOC容器管理(注解+掃描)
        2、開啟AspectJ的自動代理,為目標對象自動生成代理
        3、將切面類通過注解@Aspect標識
    -->
    <context:component-scan base-package="com.atguigu.aop.annotation"></context:component-scan>

    <aop:aspectj-autoproxy />
</beans>

執(zhí)行測試:

public class CalculatorTest {

    private Logger logger = LoggerFactory.getLogger(CalculatorTest.class);

    @Test
    public void testAdd(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        Calculator calculator = ac.getBean( Calculator.class);
        int add = calculator.add(1, 1);
        logger.info("執(zhí)行成功:"+add);
    }

}

4、各種通知

  • 前置通知:使用@Before注解標識,在被代理的目標方法執(zhí)行
  • 返回通知:使用@AfterReturning注解標識,在被代理的目標方法成功結束后執(zhí)行(壽終正寢
  • 異常通知:使用@AfterThrowing注解標識,在被代理的目標方法異常結束后執(zhí)行(死于非命
  • 后置通知:使用@After注解標識,在被代理的目標方法最終結束后執(zhí)行(蓋棺定論
  • 環(huán)繞通知:使用@Around注解標識,使用try…catch…finally結構圍繞整個被代理的目標方法,包括上面四種通知對應的所有位置

各種通知的執(zhí)行順序:

  • Spring版本5.3.x以前:
    • 前置通知
    • 目標操作
    • 后置通知
    • 返回通知或異常通知
  • Spring版本5.3.x以后:
    • 前置通知
    • 目標操作
    • 返回通知或異常通知
    • 后置通知

5、切入點表達式語法

①作用
spring之面向切面:AOP(2),Spring&amp;SpringMVC,spring,java,后端
②語法細節(jié)

  • 用*號代替“權限修飾符”和“返回值”部分表示“權限修飾符”和“返回值”不限

  • 在包名的部分,一個“*”號只能代表包的層次結構中的一層,表示這一層是任意的。

    • 例如:*.Hello匹配com.Hello,不匹配com.atguigu.Hello
  • 在包名的部分,使用“*…”表示包名任意、包的層次深度任意

  • 在類名的部分,類名部分整體用*號代替,表示類名任意

  • 在類名的部分,可以使用*號代替類名的一部分

    • 例如:*Service匹配所有名稱以Service結尾的類或接口
  • 在方法名部分,可以使用*號表示方法名任意

  • 在方法名部分,可以使用*號代替方法名的一部分

    • 例如:*Operation匹配所有方法名以Operation結尾的方法
  • 在方法參數(shù)列表部分,使用(…)表示參數(shù)列表任意

  • 在方法參數(shù)列表部分,使用(int,…)表示參數(shù)列表以一個int類型的參數(shù)開頭

  • 在方法參數(shù)列表部分,基本數(shù)據(jù)類型和對應的包裝類型是不一樣的

    • 切入點表達式中使用 int 和實際方法中 Integer 是不匹配的
  • 在方法返回值部分,如果想要明確指定一個返回值類型,那么必須同時寫明權限修飾符

    • 例如:execution(public int Service.(…, int)) 正確
      例如:execution(
      int *…Service.(…, int)) 錯誤
      spring之面向切面:AOP(2),Spring&amp;SpringMVC,spring,java,后端

6、重用切入點表達式

①聲明

@Pointcut("execution(* com.atguigu.aop.annotation.*.*(..))")
public void pointCut(){}

②在同一個切面中使用

@Before("pointCut()")
public void beforeMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}

③在不同切面中使用

@Before("com.atguigu.aop.CommonPointCut.pointCut()")
public void beforeMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}

7、獲取通知的相關信息

①獲取連接點信息

獲取連接點信息可以在通知方法的參數(shù)位置設置JoinPoint類型的形參

@Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
    //獲取連接點的簽名信息
    String methodName = joinPoint.getSignature().getName();
    //獲取目標方法到的實參信息
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",參數(shù):"+args);
}

②獲取目標方法的返回值

@AfterReturning中的屬性returning,用來將通知方法的某個形參,接收目標方法的返回值

@AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->返回通知,方法名:"+methodName+",結果:"+result);
}

③獲取目標方法的異常

@AfterThrowing中的屬性throwing,用來將通知方法的某個形參,接收目標方法的異常

@AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->異常通知,方法名:"+methodName+",異常:"+ex);
}

8、環(huán)繞通知

@Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    Object result = null;
    try {
        System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行之前");
        //目標方法的執(zhí)行,目標方法的返回值一定要返回給外界調用者
        result = joinPoint.proceed();
        System.out.println("環(huán)繞通知-->目標對象方法返回值之后");
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        System.out.println("環(huán)繞通知-->目標對象方法出現(xiàn)異常時");
    } finally {
        System.out.println("環(huán)繞通知-->目標對象方法執(zhí)行完畢");
    }
    return result;
}

9、切面的優(yōu)先級

相同目標方法上同時存在多個切面時,切面的優(yōu)先級控制切面的內外嵌套順序。

  • 優(yōu)先級高的切面:外面
  • 優(yōu)先級低的切面:里面

使用@Order注解可以控制切面的優(yōu)先級:

  • @Order(較小的數(shù)):優(yōu)先級高
  • @Order(較大的數(shù)):優(yōu)先級低
    spring之面向切面:AOP(2),Spring&amp;SpringMVC,spring,java,后端

二、基于XML的AOP

1、準備工作

參考基于注解的AOP環(huán)境

2、實現(xiàn)

<context:component-scan base-package="com.atguigu.aop.xml"></context:component-scan>

<aop:config>
    <!--配置切面類-->
    <aop:aspect ref="loggerAspect">
        <aop:pointcut id="pointCut" 
                   expression="execution(* com.atguigu.aop.xml.CalculatorImpl.*(..))"/>
        <aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
        <aop:after method="afterMethod" pointcut-ref="pointCut"></aop:after>
        <aop:after-returning method="afterReturningMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
        <aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointCut"></aop:after-throwing>
        <aop:around method="aroundMethod" pointcut-ref="pointCut"></aop:around>
    </aop:aspect>
</aop:config>

總結

以上就是spring之面向切面:AOP(2)的相關知識點,希望對你有所幫助。
積跬步以至千里,積怠惰以至深淵。時代在這跟著你一起努力哦!文章來源地址http://www.zghlxwxcb.cn/news/detail-765912.html

到了這里,關于spring之面向切面:AOP(2)的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!

本文來自互聯(lián)網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處: 如若內容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • spring之面向切面:AOP(2)

    spring之面向切面:AOP(2)

    學習的最大理由是想擺脫平庸,早一天就多一份人生的精彩;遲一天就多一天平庸的困擾。各位小伙伴,如果您: 想系統(tǒng)/深入學習某技術知識點… 一個人摸索學習很難堅持,想組團高效學習… 想寫博客但無從下手,急需寫作干貨注入能量… 熱愛寫作,愿意讓自己成為更好

    2024年02月04日
    瀏覽(12)
  • Spring-AOP(面向切面)

    Spring-AOP(面向切面)

    功能接口 實現(xiàn)類 在含有日志輸出的實現(xiàn)類中可以了解到:與核心業(yè)務功能沒有關系的日志輸出加雜在模塊中,對核心業(yè)務功能有干擾。 思路:解耦 , 將附加功能從業(yè)務功能模塊中抽取出來 概念 二十三種設計模式中的一種,屬于結構型模式,它的作用就是通過提供一個代理

    2024年02月16日
    瀏覽(26)
  • [SSM]Spring面向切面編程AOP

    [SSM]Spring面向切面編程AOP

    目錄 十五、面向切面編程AOP 15.1AOP介紹 15.2AOP的七大術語 15.3切點表達式 15.4使用Spring的AOP 15.4.1準備工作 15.4.2基于AspectJ的AOP注解式開發(fā) 15.4.3基于XML配置方式的AOP(了解) 15.5AOP的實際案例:事務處理 15.6AOP的實際案例:安全日志 IoC使軟件組件松耦合。AOP讓你能夠捕捉系統(tǒng)中經

    2024年02月15日
    瀏覽(28)
  • Spring AOP(面向切面編程)和方法攔截

    Spring AOP(面向切面編程)和方法攔截 Spring是一款廣泛使用的Java開發(fā)框架,提供了豐富的功能和工具,用于簡化企業(yè)級應用程序的開發(fā)。其中一個重要的特性是面向切面編程(AOP)和方法攔截。本文將介紹Spring AOP和方法攔截的概念、工作原理以及在實際開發(fā)中的應用。 在軟

    2024年02月05日
    瀏覽(24)
  • 認識 spring AOP (面向切面編程) - springboot

    認識 spring AOP (面向切面編程) - springboot

    本篇介紹什么是spring AOP, AOP的優(yōu)點,使用場景,spring AOP的組成,簡單實現(xiàn)AOP 并 了解它的通知;如有錯誤,請在評論區(qū)指正,讓我們一起交流,共同進步! 本文開始 AOP: 面向切面編程,也就是面向某一類編程,對某一類事情進行統(tǒng)一處理; spring AOP: 是實現(xiàn)了AOP這種思想的一

    2024年02月14日
    瀏覽(29)
  • 切面的魔力:解密Spring AOP 面向切面編程

    切面的魔力:解密Spring AOP 面向切面編程

    目錄 一、AOP簡介 1.1 什么是AOP ? 1.2?什么是面向切面編程 ? 1.3?AOP 的特點 二、?AOP的基本概念解讀 2.1 AOP的基本概念 2.2 AOP 概念趣事解讀 三、代碼情景演示 3.1?編寫目標對象(超級英雄們正常的行動) 3.2 編寫通知類 3.2.1?前置通知 3.2.2 后置通知 3.2.3 異常通知 3.2.4 環(huán)繞通知

    2024年02月11日
    瀏覽(89)
  • Spring系列篇--關于AOP【面向切面】的詳解

    Spring系列篇--關于AOP【面向切面】的詳解

    目錄 一.AOP是什么 二.案例演示? 1.前置通知1.1 先準備接口 1.2然后再準備好實現(xiàn)類 1.3對我們的目標對象進行JavaBean配置? 1.4 編寫前置系統(tǒng)日志通知 1.5配置系統(tǒng)通知XML中的JavaBean 1.6 配置代理XML中的JavaBean 1.7 測試代碼開始測試 注意這里有一個報錯問題?。?! 2. 后置通知2.1 先準

    2024年02月12日
    瀏覽(20)
  • spring6-AOP面向切面編程

    spring6-AOP面向切面編程

    1、場景模擬 搭建子模塊:spring6-aop 1.1、聲明接口 聲明計算器接口Calculator,包含加減乘除的抽象方法 1.2、創(chuàng)建實現(xiàn)類 1.3、創(chuàng)建帶日志功能的實現(xiàn)類 1.4、提出問題 ①現(xiàn)有代碼缺陷 針對帶日志功能的實現(xiàn)類,我們發(fā)現(xiàn)有如下缺陷: 對核心業(yè)務功能有干擾,導致程序員在開發(fā)核

    2024年02月08日
    瀏覽(32)
  • 【Spring AOP】結合日志面向切面編程 兩種寫法

    ??????? 這里需要提前了解什么是Spring的AOP(Aspect Oriented Programming)。是在OOP(面向對象)思想的一種拓展思想。 簡單來說就是將某個代碼塊嵌入到其它的代碼塊中 。筆者先前學Spring也有學什么IoC啊AOP啊,但實際上沒有用過、就那聽過學過沒啥用的。。沒會兒就忘記了。

    2024年02月13日
    瀏覽(28)
  • 【Spring】javaBean、依賴注入、面向切面AOP、使用注解開發(fā)

    【Spring】javaBean、依賴注入、面向切面AOP、使用注解開發(fā)

    有一定規(guī)范的Java實體類,類內提供了一些公共方法以便外界對該對象的內部屬性進行操作 所有屬性都是private,所有的屬性都可以通過get/set方法進行訪問,同時還需要有一個無參構造(默認就有) 高內聚,低耦合是現(xiàn)代軟件的開發(fā)的設計模式 之前編寫的圖書管理系統(tǒng)具有高

    2024年02月08日
    瀏覽(57)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包