目录
  • 二、spring接口方式实现aop步骤

    spring 提供了很多的实现aop的方式:spring 接口方式,schema配置方式和注解.

    本文重点介绍spring使用接口方式实现aop. 研究使用接口方式实现aop, 以了解为目的. 更好地理解spring使用动态代理实现aop. 通常我们使用的更多的是使用注解的方式实现aop

    下面来看看如何实现接口方式的aop

    一. 环境准备

    要在项目中使用spring aop 则需要在项目中导入除了spring jar包之外, 还需要引入aspectjrt.jar,aspectjweaver.jar,aopalliance.jar ,spring-aop-3.2.0.m2.jar和cglib.jar

    二、spring接口方式实现aop步骤

    使用spring aop接口方式实现aop, 可以通过自定义通知来供spring aop识别. 常见的自己定义通知有:前置通知, 后置通知, 返回通知, 异常通知, 环绕通知. 对应实现的接口是:

    1. 前置通知: methodbeforeadvice
    2. 后置通知: afteradvice
    3. 返回通知:afterreturningadvice
    4. 异常通知:throwsadvice
    5. 环绕通知:methodinterceptor

    实现步骤如下:

    1. 业务接口实现

    package com.lxl.www.aop.interfaceaop;
    
    /**
     * 使用接口方式实现aop, 默认通过jdk的动态代理来实现. 非接口方式, 使用的是cglib实现动态代理
     *
     * 业务接口类-- 计算器接口类
     *
     * 定义三个业务逻辑方法
     */
    public interface ibasecalculate {
    
        int add(int numa, int numb);
    
        int sub(int numa, int numb);
    
        int div(int numa, int numb);
    
        int multi(int numa, int numb);
    
        int mod(int numa, int numb);
    
    }

    2. 业务类

    package com.lxl.www.aop.interfaceaop;//业务类,也是目标对象
    
    import com.lxl.www.aop.calculate;
    
    import org.springframework.aop.framework.aopcontext;
    import org.springframework.stereotype.service;
    
    /**
     * 业务实现类 -- 基础计算器
     */
    @service
    public class basecalculate implements ibasecalculate {
    
        @override
        public int add(int numa, int numb) {
            system.out.println("执行目标方法: add");
            return numa + numb;
        }
    
        @override
        public int sub(int numa, int numb) {
            system.out.println("执行目标方法: sub");
            return numa - numb;
        }
    
        @override
        public int multi(int numa, int numb) {
            system.out.println("执行目标方法: multi");
            return numa * numb;
        }
    
        @override
        public int div(int numa, int numb) {
            system.out.println("执行目标方法: div");
            return numa / numb;
        }
    
        @override
        public int mod(int numa, int numb) {
            system.out.println("执行目标方法: mod");
    
            int retval = ((calculate) aopcontext.currentproxy()).add(numa, numb);
            return retval % numa;
        }
    }

    3. 通知类

    前置通知

    package com.lxl.www.aop.interfaceaop;
    
    import org.springframework.aop.methodbeforeadvice;
    import org.springframework.stereotype.component;
    
    import java.lang.reflect.method;
    
    /**
     * 定义前置通知
     */
    @component
    public class basebeforeadvice implements methodbeforeadvice {
    
        /**
         *
         * @param method 切入的方法
         * @param args 切入方法的参数
         * @param target 目标对象
         * @throws throwable
         */
        @override
        public void before(method method, object[] args, object target) throws throwable {
            system.out.println("===========进入beforeadvice()============");
    
            system.out.println("目标对象:" + target);
            system.out.println("方法名: "+method);
    
            system.out.println("即将进入切入点方法");
        }
    }

    后置通知

    package com.lxl.www.aop.interfaceaop;
    
    import org.aspectj.lang.annotation.afterreturning;
    import org.springframework.aop.afteradvice;
    import org.springframework.aop.afterreturningadvice;
    import org.springframework.stereotype.component;
    
    import java.lang.reflect.method;
    
    public class baseafterreturnadvice implements afterreturningadvice {
    
        /**
         *
         * @param returnvalue 切入点执行完方法的返回值,但不能修改
         * @param method 切入点方法
         * @param args 切入点方法的参数数组
         * @param target 目标对象
         * @throws throwable
         */
        @override
        public void afterreturning(object returnvalue, method method, object[] args, object target) throws throwable {
            system.out.println("==========进入afterreturning()=========== \n");
            system.out.println("切入点方法执行完成");
    
            system.out.println("后置通知--目标对象:" + target);
            system.out.println("后置通知--方法名: "+method);
            system.out.println("后置通知--方法入参: "+ args.tostring());
            system.out.println("后置通知--方法返回值: "+ returnvalue);
        }
    }

    异常通知

    package com.lxl.www.aop.interfaceaop;
    
    import org.springframework.aop.throwsadvice;
    import org.springframework.stereotype.component;
    
    import java.lang.reflect.method;
    @component
    public class baseafterthrowsadvice implements throwsadvice {
    
        /**
         * @param method    可选:切入的方法
         * @param args      可选:切入的方法的参数
         * @param target    可选:目标对象
         * @param throwable 必填 : 异常子类,出现这个异常类的子类,则会进入这个通知。
         */
        public void afterthrowing(method method, object[] args, object target, throwable throwable) {
            system.out.println("出错啦");
        }
    }

    环绕通知

    package com.lxl.www.aop.interfaceaop;
    
    import org.aopalliance.intercept.methodinterceptor;
    import org.aopalliance.intercept.methodinvocation;
    import org.springframework.stereotype.component;
    
    import java.lang.reflect.method;
    
    /**
     * 环绕通知
     */
    @component
    public class basearoundadvice implements methodinterceptor {
    
        /**
         * invocation :连接点
         */
        @override
        public object invoke(methodinvocation invocation) throws throwable {
            system.out.println("===========around环绕通知方法 开始===========");
    
            // 调用目标方法之前执行的动作
            system.out.println("环绕通知--调用方法之前: 执行");
    
            // 调用方法的参数
            object[] args = invocation.getarguments();
            // 调用的方法
            method method = invocation.getmethod();
            // 获取目标对象
            object target = invocation.getthis();
            system.out.println("输入参数:" + args[0] + ";" + method + ";" + target);
    
            // 执行完方法的返回值:调用proceed()方法,就会触发切入点方法执行
            object returnvalue = invocation.proceed();
    
            system.out.println("环绕通知--调用方法之后: 执行");
          
            system.out.println("输出参数:" + args[0] + ";" + method + ";" + target + ";" + returnvalue);
    
            system.out.println("===========around环绕通知方法  结束===========");
    
            return returnvalue;
        }
    }

    4. 自定义切## 点

    package com.lxl.www.aop.interfaceaop;
    
    /**
     * 切点
     *
     * 继承namematchmethodpointcut类,来用方法名匹配
     */
    import org.springframework.aop.support.namematchmethodpointcut;
    import org.springframework.stereotype.component;
    
    import java.lang.reflect.method;
    
    @component
    public class pointcut extends namematchmethodpointcut {
    
        private static final long serialversionuid = 3990456017285944475l;
    
        @suppresswarnings("rawtypes")
        @override
        public boolean matches(method method, class targetclass) {
            // 设置单个方法匹配
            this.setmappedname("add");
            // 设置多个方法匹配
            string[] methods = { "add", "div" };
          
            //也可以用“ * ” 来做匹配符号
            // this.setmappedname("get*");
          
            this.setmappednames(methods);
    
            return super.matches(method, targetclass);
        }
    }

    5.配置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:p="http://www.springframework.org/schema/p"
           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-3.0.xsd
    
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-3.0.xsd
    
             http://www.springframework.org/schema/aop
              http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
    >
    
        <!-- ==============================aop配置================================ -->
        <!-- 声明一个业务类 -->
        <bean id="basecalculate" class="com.lxl.www.aop.interfaceaop.basecalculate"/>
    
        <!-- 声明通知类 -->
        <bean id="basebefore" class="com.lxl.www.aop.interfaceaop.basebeforeadvice"/>
        <bean id="baseafterreturn" class="com.lxl.www.aop.interfaceaop.baseafterreturnadvice"/>
        <bean id="baseafterthrows" class="com.lxl.www.aop.interfaceaop.baseafterthrowsadvice"/>
        <bean id="basearound" class="com.lxl.www.aop.interfaceaop.basearoundadvice"/>
    
        <!-- 指定切点匹配类 -->
        <bean id="pointcut" class="com.lxl.www.aop.interfaceaop.pointcut"/>
    
        <!-- 包装通知,指定切点 -->
        <bean id="matchbeforeadvisor" class="org.springframework.aop.support.defaultpointcutadvisor">
            <property name="pointcut">
                <ref bean="pointcut"/>
            </property>
            <property name="advice">
                <ref bean="basebefore"/>
            </property>
        </bean>
    
        <!-- 使用proxyfactorybean 产生代理对象 -->
        <bean id="businessproxy" class="org.springframework.aop.framework.proxyfactorybean">
            <!-- 代理对象所实现的接口 ,如果有接口可以这样设置 -->
            <property name="proxyinterfaces">
                <value>com.lxl.www.aop.interfaceaop.ibasecalculate</value>
            </property>
    
            <!-- 设置目标对象 -->
            <property name="target">
                <ref bean="basecalculate"/>
            </property>
            <!-- 代理对象所使用的拦截器 -->
            <property name="interceptornames">
                <list>
                    <value>matchbeforeadvisor</value>
                    <value>baseafterreturn</value>
                    <value>basearound</value>
                </list>
            </property>
        </bean>
    </beans>

    6. 方法入口

    package com.lxl.www.aop.interfaceaop;
    
    import org.springframework.context.applicationcontext;
    import org.springframework.context.annotation.annotationconfigapplicationcontext;
    import org.springframework.context.support.classpathxmlapplicationcontext;
    
    public class interfacemainclass{
    
        public static void main(string[] args) {
            applicationcontext context = new classpathxmlapplicationcontext("aop/aop.xml");
            basecalculate calculate = (basecalculate) context.getbean("basecalculate");
            calculate.add(1, 3);
        }
    }

    三. 分析

    各种类型通知的执行顺序: 前置方法会在切入点方法之前执行,后置会在切入点方法执行之后执行,环绕则会在切入点方法执行前执行同事方法结束也会执行对应的部分。主要是调用proceed()方法来执行切入点方法。来作为环绕通知前后方法的分水岭
    在xml 配置 businessproxy这个bean的时候,proxyfactorybean类中指定了,proxyinterfaces参数。这里把他配置了ibasecalculate接口。因为在项目开发过程中,往往业务类都会有对应的接口,以方便利用ioc解耦。但spring aop却也能支持没有接口的代理。这就是为什么需要导入cglib.jar包了。看过spring的源码,知道在目标切入对象如果有实现接口,spring会默认使用jdk动态代理来实现代理类。如果没有接口,则会通过cglib来实现代理类。

    这个业务类现在有 前置通知,后置通知,环绕三个通知同时作用,可能以及更多的通知进行作用。那么这些通知的执行顺序是怎么样的?就这个例子而言,同时实现了三个通知。在例 子xml中,则显示执行before通知,然后执行around的前处理,执行切点方法,再执行return处理。最后执行around的后处理。经过测 试,知道spring 处理顺序是按照xml配置顺序依次处理通知,以队列的方式存放前通知,以压栈的方式存放后通知。所以是前通知依次执行,后通知到切入点执行完之后,从栈里 在后进先出的形式把后通知执行。

    在实现过程中发现通知执行对应目标对象的整个类中的方法,如何精确到某个方法,则需要定义一个切点匹配的方式:spring提供了方法名匹配或正则方式来匹配。然后通过defaultpointcutadvisor来包装通知,指定切点。

    使用接口方式配置起来,可见代码还是非常的厚重的,定义一个切面就要定义一个切面类,然而切面类中,就一个通知方法,着实没有必要。所以spring提供了,依赖aspectj的schema配置和基于aspectj 注解方式。这两种方式非常简单方便使用,也是项目中普遍的使用方式。

    到此这篇关于spring aop使用接口方式实现的文章就介绍到这了,更多相关spring aop 接口实现内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!