Spring---AOP

微信圖片_20200505203448.jpg
                                                   不是所有的魚兒能生活在同一片海洋

AOP

概念: 面向切面編程(Aspect Oriented Programming),利用AOP可以對(duì)業(yè)務(wù)邏輯的各個(gè)部分進(jìn)行隔離。從而使得業(yè)務(wù)邏輯各部分之間的耦合度降低,提高程序的可重用性,同時(shí)提高開發(fā)效率。

底層原理

  1. 使用動(dòng)態(tài)代理
  • 有接口 使用JDK動(dòng)態(tài)代理

JDK動(dòng)態(tài)代理

   創(chuàng)建UserDao接口實(shí)現(xiàn)類代理對(duì)象

  使用JDK動(dòng)態(tài)代理,使用Proxy類里面的方法創(chuàng)建代理對(duì)象
package com.aop.dao;

public interface UserDao {
    public int add(int a, int b);

    public String update(String id);

}

package com.aop.dao;


public class UserDaoImpl implements UserDao{

    @Override
    public int add(int a, int b) {
        return a + b;
    }

    @Override
    public String update(String id) {
        return id;
    }
}

package com.aop.dao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxy {

    public static void main(String[] args) {

        Class[] interfaces = {UserDao.class};
        UserDaoImpl userDao = new UserDaoImpl();
        UserDao instance = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = instance.add(1, 2);
        System.out.println(add);
    }

}


// 創(chuàng)建代理對(duì)象
class UserDaoProxy implements InvocationHandler {
    // 增強(qiáng)邏輯
    // 把創(chuàng)建的是誰(shuí)的代理對(duì)象,把誰(shuí)傳遞過(guò)來(lái)
    // 有參構(gòu)造

    private Object object;
    public UserDaoProxy(Object object) {
        this.object = object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object invoke = method.invoke(object, args);
        
        return invoke;
    }
}

AOP(術(shù)語(yǔ))

  連接點(diǎn): 類中可被增強(qiáng)的方法

  切入點(diǎn):  實(shí)際被真正增強(qiáng)的方法

  通知(增強(qiáng)):   實(shí)際增強(qiáng)的邏輯部分稱為通知

                              通知有多種類型

                            (1)前置通知

                            (2)后置通知

                            (3)環(huán)繞通知

                            (4)異常通知

                            (5)最終通知

  切面:把通知應(yīng)用到切入點(diǎn)過(guò)程



AOP操作(準(zhǔn)備)

    Spring框架一般都是基于AspectJ實(shí)現(xiàn)AOP操作

    AspectJ:不是Spring組成部分,獨(dú)立AOP框架。一般把AspectJ和Spring框架一起使用,進(jìn)行AOP操作

    方式:

        基于xml配置文件

        基于注解方式實(shí)現(xiàn)(使用)

    引入相關(guān)依賴

        ![image-20210404193509709.png](https://upload-images.jianshu.io/upload_images/19868552-b00e34ca4c7d03cc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

切入點(diǎn)表達(dá)式

作用:知道對(duì)那個(gè)類里面的那個(gè)方法進(jìn)行增強(qiáng)

語(yǔ)法結(jié)構(gòu):

     execution(權(quán)限修飾符  返回類型  類全路徑  方法名稱  參數(shù)列表)
  1. AspectJ注解

創(chuàng)建類,在類中定義方法

package com.aopanro;

public class User {
    public void add() {
        System.out.println("add....");
    }
}

創(chuàng)建增強(qiáng)類

  創(chuàng)建不同的方法代表不同的通知類型
package com.aopanro;

public class UserProxy {
    // 前置通知
    public void before() {
        System.out.println("before....");
    }
}

進(jìn)行通知配置

  • 在Spring配置文件中,開啟注解掃描

  • 使用注解創(chuàng)建User和UserProxy對(duì)象

  • 在增強(qiáng)類上面添加注解@Aspect

  • 在Spring配置文件中開啟生成代理對(duì)象

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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">
            <!--   開啟直接掃描     -->
            <context:component-scan base-package="com.aopanro"></context:component-scan>
            <!--  開啟Aspect生成代理對(duì)象  -->
            <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>
    
 ```java
 package com.aopanro;
 
 import org.springframework.stereotype.Component;
 
 @Component
 public class User {
     public void add() {
         System.out.println("add....");
     }
 }
 ```

 ```java
 package com.aopanro;
 
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Before;
 import org.springframework.stereotype.Component;
 
 @Component
 @Aspect
 public class UserProxy {
     // 前置通知
     public void before() {
         System.out.println("before....");
     }
 }
 ```

 配置不同類型通知

 在增強(qiáng)類的里面,在作為通知方法上面添加通知類型注解,使用切入點(diǎn)表達(dá)式配置

 ```java
 package com.aopanro;
 
         import org.aspectj.lang.ProceedingJoinPoint;
         import org.aspectj.lang.annotation.*;
         import org.springframework.stereotype.Component;
 
 @Component
 @Aspect
 public class UserProxy {
     @Pointcut(value = "execution(* com.aopanro.User.add(..))")
     public void pointDemo() {
 
     }
     // 前置通知
     @Before(value = "pointDemo()")
     public void before() {
         System.out.println("before....");
     }
 
     @After(value = "pointDemo()")
     public void after() {
         System.out.println("after....");
     }
 
     @AfterThrowing(value = "pointDemo()")
     public void afterThrow() {
         System.out.println("afterThrow....");
     }
 
     @AfterReturning(value = "pointDemo()")
     public void afterReturning() {
         System.out.println("afterReturning....");
     }
 
     @Around(value = "pointDemo()")
     public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
         System.out.println("around之前。。。");
         proceedingJoinPoint.proceed();
         System.out.println("around之后。。。");
     }
 
 }
 
 
 ```

 @Order() 數(shù)值越小優(yōu)先級(jí)越高
  1. AspectJ配置文件

    (1)創(chuàng)建兩個(gè)類,一個(gè)增強(qiáng)類一個(gè)被增強(qiáng)類

    (2)在Spring配置文件中創(chuàng)建兩個(gè)類對(duì)象

    package com.aopxml;
    
    public class Book {
        public void buy() {
            System.out.println("buy.....");
        }
    }
    
    package com.aopxml;
    
    public class BookProxy {
    
        public void before() {
            System.out.println("before...");
        }
    
    }
    

    (3)在Spring配置文件中配置切入點(diǎn)

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           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">
        <bean id="book" class="com.aopxml.Book"></bean>
        <bean id="bookProxy" class="com.aopxml.BookProxy"></bean>
    
        <!--  配置aop增強(qiáng)  -->
        <aop:config>
            <!--   配置切入點(diǎn)     -->
            <aop:pointcut id="p" expression="execution(* com.aopxml.Book.buy(..))"/>
            <!--    配置切面    -->
            <aop:aspect ref="bookProxy">
                <!--    增強(qiáng)作用在具體方法上        -->
                <aop:before method="before" pointcut-ref="p"></aop:before>
            </aop:aspect>
        </aop:config>
    </beans>
    

    完全注解方式

    package com.config;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.EnableAspectJAutoProxy;
    
    @Configuration
    @ComponentScan(basePackages = {"com.aopanro"})
    @EnableAspectJAutoProxy(proxyTargetClass = true)
    public class ConfigAop {
    }
    
  • 沒(méi)有接口 使用CGLIB動(dòng)態(tài)代理

CGLIB動(dòng)態(tài)代理

       創(chuàng)建當(dāng)前類子類的代理對(duì)象,增強(qiáng)類的方法
package com.aop.service;

public class User {
    public void add() {
        // ......
    }
}
package com.aop.service;

public class SubUser extends User{
    @Override
    public void add() {
        super.add();
        // 增強(qiáng)邏輯
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring AOP 模塊,是 Spring 框架體系結(jié)構(gòu)中十分重要的內(nèi)容,該模塊中提供了面向切面編程實(shí)現(xiàn) 。本章...
    遼A丶孫悟空閱讀 1,222評(píng)論 2 14
  • 一、概要 Spring加入了對(duì)AOP編程支持,利用AOP的思想結(jié)合Spring的一些API可以實(shí)現(xiàn)核心業(yè)務(wù)與輔助業(yè)...
    任未然閱讀 335評(píng)論 0 1
  • 目錄 1. Web MVC發(fā)展史歷程2.Spring概要3.Spring-依賴注入概要(IOC)4.屬性注入的三種...
    唯老閱讀 1,698評(píng)論 0 3
  • 初識(shí) AOP(傳統(tǒng)程序) Tips:如果想要快速查閱的朋友,可以直接跳轉(zhuǎn)到 初識(shí)AOP(Spring 程序)這一大...
    BWH_Steven閱讀 873評(píng)論 0 1
  • 一、AOP概述AOP(Aspect Orient Programming),面向切面編程,是面向?qū)ο缶幊蘋OP的一...
    神的孩子都該跳舞閱讀 386評(píng)論 0 1

友情鏈接更多精彩內(nèi)容