aop的底层实现

本文详细介绍了AOP(面向切面编程)的底层实现,包括JDK动态代理和CGLIB动态代理的原理。讲解了如何创建接口实现类的代理对象以及创建当前类子类的代理对象。此外,还探讨了AOP中的术语,如连接点、切入点、通知类型和切面,并介绍了基于AspectJ的AOP操作,包括XML配置和注解方式的实现。最后,提到了如何设置增强类的执行优先级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AOP底层使用的是动态代理

(1)动态代理分为两种情况
有接口,使用JDK动态代理
没有接口,使用CGLIB动态代理

JDK动态代理 (创建接口实现类的代理对象

1、怎么实现?
通过使用java提供的Proxy类中的方法创建代理对象
调用newProxyInstance方法
2、newProxyInstance方法
三个参数:(1)类加载器;
(2)增强方法所在的类,这个类实现的接口,支持多个接口
(3)实现InvocationHandler,创建代理对象,写增强方法

3、实现过程演示
(1)创建接口,定义方法

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

(2)创建接口类的实现类

public class UserDaoImp implements UserDao {
    /**
     * 实现UserDao接口中的add方法
     * @param a
     * @param b
     * @return
     */
    public int add (int a, int b) {
        return a+b;
    }
}

(3)具体实现

/**
 * JDK动态代理
 */
public class JDKProxy {
    public static void main (String[] args) {
        /**
         * interfaces 是增强方法所在的类组成的数组
         */
        Class[] interfaces={UserDao.class};

//        Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
//                return null;
//            }
//        }); 通过匿名内部类创建InvocationHandler对象
        /**
         * 获取代理对象
         * JDKProxy.class.getClassLoader() 类加载器
         * interfaces 增强方法所在的类组成的数组
         * new UserDaoProxy(new UserDaoImp()) 创建代理对象
         */
        UserDao  userDao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(new UserDaoImp()));
        userDao.add(2,6);
    }
}

/**
 * 创建代理对象
 * 通过实现InvocationHandler接口中的 invoke方法
 */
class UserDaoProxy implements InvocationHandler{

    /**
     * 将需要增强的对象 传递进行
     */
    private Object object;

    /**
     * 通过有参数构造传递 需要增强的对象
     * @param object
     */
    UserDaoProxy (Object object) {
        this.object = object;
    }

    /**
     * invoke方法中实现增强的逻辑
     * @param proxy     增强的对象
     * @param method    增强的方法
     * @param args      增强方法的参数列表
     * @return
     * @throws Throwable
     */
    public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("方法之前执行...."+method.getName()+"传入的参数"+ Arrays.toString(args));

        /**
         * 被增强方法的执行
         * 两个参数 增强的对象object  参数列表args
         */

         method.invoke(object, args);


        //方法之后
        System.out.println("方法之后执行...."+method.getName());

        /**
         * 注意 上面定义是返回Object类,直接返回null 会抛出 java.lang.NullPointerException 异常
         *
         */
        return null;
    }
}

CGLIB动态代理 (创建当前类子类的代理对象)

    这部分笔者还没深入了解 暂时空置,等总结完后再来做补充~~~~~

AOP(术语)

1、连接点
类中可以被增强的方法 就叫连接点
2、切入点
实际被真正增强的方法,称为切入点
3、通知(增强)
(1)实际增强中增强的逻辑部分称之为 通知(增强)
(2)有多种通知类型
~ 前置通知
~ 后置通知
~ 环绕通知
~异常通知
~ 最终通知
4、切面
把通知应该到切入点的过程 叫做切面

AOP操作(准备阶段)

1、Spring框架一般是基于ApsectJ实现AOP操作
什么是AspectJ ?
AspectJ是一个独立的AOP框架,一般与Spring框架搭配使用,进行aop操作

2、基于AspectJ实现AOP操作
(1)基于xml配置文件实现
(2)基于注解方式实现

3、引入依赖

<!--        基于AspectJ实现aop操作需要的依赖-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sourceforge.cglib/com.springsource.net.sf.cglib -->
        <dependency>
            <groupId>net.sourceforge.cglib</groupId>
            <artifactId>com.springsource.net.sf.cglib</artifactId>
            <version>2.2.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
            <scope>runtime</scope>
        </dependency>

4、切入点表达式
(1)作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构:
execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]))

AOP操作(AspectJ注解)

1、创建被增强类,在类中定义方法

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

2、创建增强类(编写增强逻辑)

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

3、进行通知的配置
(1)在Spring 的配置文件中,开启主键扫描
(2)使用注解创建对象
(3)在增强类上面添加注解@Aspect,生成类的代理对象
(4)在Spring配置文件中开启生成代理对象

4、配置不同类型的通知

@Component
@Aspect
public class UserProxy {
    /**
     * 前置通知
     */
    @Before(value = "execution(* AOP.AspectJ.User.add(..))")
    public void before(){
        System.out.println("before....");
    }
    /**
     * 公共切入点的抽取
     */
    @Pointcut(value = "execution(* AOP.AspectJ.User.add(..))")
    public void pointExtract(){}
    /**
     * 最终通知
     */
    @After(value = "pointExtract()")
    public void after(){
        System.out.println("after....");
    }
    /**
     * 返回通知
     */
    @AfterReturning(value = "pointExtract()")
    public void afterReturning(){
        System.out.println("afterReturning....");
    }

    /**
     * 异常通知
     */
    @AfterThrowing(value = "pointExtract()")
    public void afterThrowing(){
        System.out.println("afterThrowing....");
    }
    /**
     * 环绕通知
     */
    @Around(value = "pointExtract()")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前....");

        //执行被增强的方法
        proceedingJoinPoint.proceed();


        System.out.println("环绕之后....");
    }
}

5、公共切入点的抽取

    /**
     * 公共切入点的抽取
     */
    @Pointcut(value = "execution(* AOP.AspectJ.User.add(..))")
    public void pointExtract(){}

6、多个增强类作用于一个类上, 设置增强类执行的优先级
添加注解@Order(数值)

@Component
@Aspect
@Order(2)
public class UserProxy2 {
}

AOP操作(AspectJ配置文件)

1、创建被增强类和增强类

/**
 * 被增强类
 */
public class Book {
    public void add(){
        System.out.println("方法被调用...");
    }
}
/**
 * 增强类
 */
public class BookProxy {
    public void before(){
        System.out.println("before..");
    }
}

配置xml文件

<?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">
<!--    创建对象-->
    <bean id="book" class="AOP.AspectJ.xml配置方式.Book"></bean>
    <bean id="bookProxy" class="AOP.AspectJ.xml配置方式.BookProxy"></bean>

    <!--配置aop增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* AOP.AspectJ.xml配置方式.Book.add(..))"/>

        <!--
            配置切面
            ref 引入增强类
         -->
        <aop:aspect ref="bookProxy">
            <!--增强作用在具体的方法上面-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值