当前位置: 移动技术网 > IT编程>开发语言>Java > Spring -- AOP

Spring -- AOP

2019年09月22日  | 移动技术网IT编程  | 我要评论

一、aop

1、什么是aop

  aop(aspect-oriented programming,面向切面编程),通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。利用aop可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
  可以理解为是oop(object-oriented programing,面向对象编程)的补充和完善。oop引入封装、继承和多态性等概念来建立一种对象层次结构(可以理解为从上到下关系)。 简单的说,oop是将 多个类似的对象的属性与行为封装在一起,并对其进行操作。而aop是将 不同的对象的 相同行为 封装在一起,并进行操作(可以理解为从左到右的关系)。
  比如:日志文件,使用oop时,在不同的对象中可能需要进行同样的日志打印操作,这些代码大量重复出现,代码冗余且重用率低。而使用aop后,其可以将这些相同的日志打印操作抽取出来,并进行一系列操作,最终降低代码冗余。

2、基本概念

(1)横切(cross-cutting)代码:
  散布在各个类中,但与核心代码无关的代码。可以理解为 与业务代码无关,但是被经常使用到的代码。比如打印日志。

(2)核心关注点:
  可以理解为 主要的业务流程。

(3)横切关注点:
  可以理解为 与业务流程无关,但又出现在业务流程中的流程。比如:日志、权限认证、事务处理等。

(4)切面(aspect):
  一种模块化机制,横切关注点的模块化,可以理解为 将各个类中的公共行为封装到一个可重用模块。

(5)连接点(join point):
  连接点指的是在程序运行过程中,能够插入切面的一个点,这个点可以是类的某个方法调用前、调用后、方法抛出异常后等。切面代码可以利用这些点插入到应用的正常流程之中,并添加行为。

(6)通知/增强(advice):
  在特定的连接点,aop框架执行的动作。
  分类:
    前置通知(before):在目标方法被调用之前调用通知功能。
    后置通知(after):在目标方法完成之后调用通知,无论该方法是否发生异常。
    后置返回通知(after-returning):在目标方法成功执行之后调用通知。
    后置异常通知(after-throwing):在目标方法抛出异常后调用通知。
    环绕通知(around):通知包裹了被通知的方法,在被通知的方法调用之前和调用之后执行自定义的行为。

(7)切点(pointcut):
  指的是一个通知将被引发的一系列连接点的集合。aop 通过切点定位到特定的连接点。切点和连接点不是一对一的关系,一个切点匹配多个连接点,切点通过 org.springframework.aop.pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。每个类都可以拥有多个连接点。

(8)引入(introduction):
  添加方法或字段到被通知的类。 spring允许引入新的接口到任何被通知的对象。

(9)目标对象(target object):
  包含连接点的对象。也被称作被通知或被代理对象。

(10)aop代理(aop proxy):
  aop框架创建的对象,包含通知。 在spring中,aop代理可以是jdk动态代理或者cglib代理。

(11)织入(weaving):
  织入描述的是把切面应用到目标对象来创建新的代理对象的过程。 spring aop 的切面是在运行时被织入,原理是使用了动态代理技术。spring支持两种方式生成代理对象:jdk动态代理和cglib,默认的策略是如果目标类是接口,则使用jdk动态代理技术(只对实现接口的类产生代理对象),否则使用cglib来生成代理。

 

二、aop的使用

1、小案例分析

  现有功能:一个简单的计算器,能进行简单的加减乘除。

【实例一:】

【calculator.java】
package com.company;

/**
 * 计算器接口,定义常用方法
 */
public interface calculator {
    /**
     * 加法操作
     * @param a 实数
     * @param b 实数
     * @return 相加结果
     */
    public double add(double a, double b);

    /**
     * 减法操作
     * @param a 实数
     * @param b 实数
     * @return 相减结果
     */
    public double sub(double a, double b);

    /**
     * 乘法操作
     * @param a 实数
     * @param b 实数
     * @return 相乘结果
     */
    public double mul(double a, double b);

    /**
     * 除法操作
     * @param a 实数
     * @param b 实数
     * @return 相除结果
     */
    public double div(double a, double b);
}


【calculatorimpl.java】
package com.company;

/**
 * 计算器实现类,实现常用方法
 */
public class calculatorimpl implements calculator {
    @override
    public double add(double a, double b) {
        return a + b;
    }

    @override
    public double sub(double a, double b) {
        return a - b;
    }

    @override
    public double mul(double a, double b) {
        return a * b;
    }

    @override
    public double div(double a, double b) {
        if(b == 0){
            system.out.println("除数不能为0");
            return 0;
        }
        return a / b;
    }
}


【main.java】
package com.company;

/**
 * 测试类
 */
public class main {

    public static void main(string[] args) {
        calculator calculator = new calculatorimpl();
        double a = 3.0;
        double b = 2.0;
        system.out.println("a + b = " + calculator.add(a, b)); // a + b = 5.0
        system.out.println("a - b = " + calculator.sub(a, b)); // a - b = 1.0
        system.out.println("a * b = " + calculator.mul(a, b)); // a * b = 6.0
        system.out.println("a / b = " + calculator.div(a, b)); // a / b = 1.5
    }
}
}

 

  需增加的功能:每次加减乘除的前后,都需要进行打印日志操作。

2、不使用aop时

(1)思路:在加减乘除方法的前后,可以增加一个方法调用,进行日志输出。
(2)实现:(在实例一的基础上修改)

【实例二:】

【calculatorimpl.java】
package com.company;

/**
 * 计算器实现类,实现常用方法
 */
public class calculatorimpl implements calculator {
    @override
    public double add(double a, double b) {
        beforemethod("add", a, b);
        double c = a + b;
        aftermethod("add", c);
        return c;
    }

    @override
    public double sub(double a, double b) {
        beforemethod("sub", a, b);
        double c = a - b;
        aftermethod("sub", c);
        return c;
    }

    @override
    public double mul(double a, double b) {
        beforemethod("mul", a, b);
        double c = a * b;
        aftermethod("mul", c);
        return c;
    }

    @override
    public double div(double a, double b) {
        beforemethod("div", a, b);
        if (b == 0) {
            system.out.println("除数不能为0");
            double c = 0;
            aftermethod("div", c);
            return 0;
        }
        double c = a / b;
        aftermethod("div", c);
        return c;
    }

    /**
     * 在业务方法前执行打印日志操作
     *
     * @param methodname 方法名
     */
    public void beforemethod(string methodname, double a, double b) {
        system.out.println("this method " + methodname + " begins with " + a + " , " + b);
    }

    /**
     * 在业务方法前执行后打印日志操作
     *
     * @param methodname 方法名
     */
    public void aftermethod(string methodname, double c) {
        system.out.println("this method " + methodname + " ends with " + c);
    }
}

【执行结果:】
this method add begins with 3.0 , 2.0
this method add ends with 5.0
a + b = 5.0
this method sub begins with 3.0 , 2.0
this method sub ends with 1.0
a - b = 1.0
this method mul begins with 3.0 , 2.0
this method mul ends with 6.0
a * b = 6.0
this method div begins with 3.0 , 2.0
this method div ends with 1.5
a / b = 1.5

 

(3)优缺点分析:
  代码直观,但是冗余严重,当修改某个部分时,可能会造成大量修改。

3、不使用aop时,代码稍微升点级

(1)实例二可能会暴露的问题:对于不同的类,可能需要使用相同的日志操作,若是使用实例二的写法,那么在每个类里面都需定义日志操作方法,造成代码冗余。
  解决: 在实例二的基础上,将日志操作抽取出来,形成一个类。当需要使用日志时,继承该类即可。


(2)实现:(在实例二的基础上修改)

【实例三:】

【message.java】
package com.company;

public class message {
    /**
     * 在业务方法前执行打印日志操作
     *
     * @param methodname 方法名
     */
    public void beforemethod(string methodname, double a, double b) {
        system.out.println("this method " + methodname + " begins with " + a + " , " + b);
    }

    /**
     * 在业务方法前执行后打印日志操作
     *
     * @param methodname 方法名
     */
    public void aftermethod(string methodname, double c) {
        system.out.println("this method " + methodname + " ends with " + c);
    }
}


【calculatorimpl.java】
package com.company;

/**
 * 计算器实现类,实现常用方法
 */
public class calculatorimpl extends message implements calculator {
    @override
    public double add(double a, double b) {
        beforemethod("add", a, b);
        double c = a + b;
        aftermethod("add", c);
        return c;
    }

    @override
    public double sub(double a, double b) {
        beforemethod("sub", a, b);
        double c = a - b;
        aftermethod("sub", c);
        return c;
    }

    @override
    public double mul(double a, double b) {
        beforemethod("mul", a, b);
        double c = a * b;
        aftermethod("mul", c);
        return c;
    }

    @override
    public double div(double a, double b) {
        beforemethod("div", a, b);
        if (b == 0) {
            system.out.println("除数不能为0");
            double c = 0;
            aftermethod("div", c);
            return c;
        }
        double c = a / b;
        aftermethod("div", c);
        return c;
    }
}


【结果:】
this method add begins with 3.0 , 2.0
this method add ends with 5.0
a + b = 5.0
this method sub begins with 3.0 , 2.0
this method sub ends with 1.0
a - b = 1.0
this method mul begins with 3.0 , 2.0
this method mul ends with 6.0
a * b = 6.0
this method div begins with 3.0 , 2.0
this method div ends with 1.5
a / b = 1.5

(3)优缺点:
  采用纵向继承(从上到下),可以减少代码冗余,但是局限性太大。

4、使用aop

(1)aop思想采用横向抽取的方式(从左到右),将日志操作封装。实质是通过动态代理来实现的。

(2)动态代理分类:
  jdk动态代理:利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用invokehandler来处理。
  cglib动态代理:利用第三方jar包,将代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。

(3)动态代理区别:
  jdk动态代理:只能对实现了接口的类产生代理。
  cglib动态代理:对没有实现接口的类产生代理对象,即针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法。

(4)jdk动态代理:
  可以参考:https://www.cnblogs.com/l-y-h/p/11111539.html#_label2

【实例四:】
核心类、接口:
    calculator.java          接口
    calculatorimpl.java      接口实现类
    calculatorproxy.java     接口实现类的代理类
    main.java                测试类

【calculator.java】
package com.company;

/**
 * 计算器接口,定义常用方法
 */
public interface calculator {
    /**
     * 加法操作
     * @param a 实数
     * @param b 实数
     * @return 相加结果
     */
    public double add(double a, double b);

    /**
     * 减法操作
     * @param a 实数
     * @param b 实数
     * @return 相减结果
     */
    public double sub(double a, double b);

    /**
     * 乘法操作
     * @param a 实数
     * @param b 实数
     * @return 相乘结果
     */
    public double mul(double a, double b);

    /**
     * 除法操作
     * @param a 实数
     * @param b 实数
     * @return 相除结果
     */
    public double div(double a, double b);
}


【calculatorimpl.java】
package com.company;

/**
 * 计算器实现类,实现常用方法
 */
public class calculatorimpl implements calculator {
    @override
    public double add(double a, double b) {
        return a + b;
    }

    @override
    public double sub(double a, double b) {
        return a - b;
    }

    @override
    public double mul(double a, double b) {
        return a * b;
    }

    @override
    public double div(double a, double b) {
        if (b == 0) {
            system.out.println("除数不能为0");
            return 0;
        }
        return a / b;
    }
}


【calculatorproxy.java】
package com.company;

import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
import java.util.arrays;

/**
 * jdk动态代理
 */
public class calculatorproxy implements invocationhandler {

    private object calculator; // 用于保存代理对象

    calculatorproxy(object calculator) {
        this.calculator = calculator;  // 获取代理的对象
    }

    @override
    public object invoke(object proxy, method method, object[] args) throws throwable {
        string methodname = method.getname(); // 获取方法名
        system.out.println("this is " + methodname + " starts with " + arrays.aslist(args));
        object obj = method.invoke(this.calculator, args);
        system.out.println("this is " + methodname + " ends with " + obj);
        return obj;
    }

    /**
     * 获取动态代理的对象
     *
     * @return 动态代理的对象
     */
    public object getjdkproxy() {
        return proxy.newproxyinstance(this.calculator.getclass().getclassloader(), this.calculator.getclass().getinterfaces(), this);
    }
}


【main.java】
package com.company;

import java.lang.reflect.proxy;

/**
 * 测试类
 */
public class main {

    public static void main(string[] args) {
        calculator realcalculator = new calculatorimpl();
        double a = 3.0;
        double b = 2.0;
//        方式一
        calculatorproxy calculatorproxy = new calculatorproxy(realcalculator);
        calculator calculator = (calculator) proxy.newproxyinstance(calculatorproxy.getclass().getclassloader(),
                realcalculator.getclass().getinterfaces(), calculatorproxy);

        system.out.println("a + b = " + calculator.add(a, b));
        system.out.println("a - b = " + calculator.sub(a, b));
        system.out.println("a * b = " + calculator.mul(a, b));
        system.out.println("a / b = " + calculator.div(a, b));

        system.out.println();
        system.out.println();
        system.out.println();
        system.out.println();
        system.out.println();

//        方式二
        calculator calculator2 = (calculator) (new calculatorproxy(realcalculator).getjdkproxy());
        system.out.println("a + b = " + calculator2.add(a, b));
        system.out.println("a - b = " + calculator2.sub(a, b));
        system.out.println("a * b = " + calculator2.mul(a, b));
        system.out.println("a / b = " + calculator2.div(a, b));
    }
}

【结果:】
this is add starts with [3.0, 2.0]
this is add ends with 5.0
a + b = 5.0
this is sub starts with [3.0, 2.0]
this is sub ends with 1.0
a - b = 1.0
this is mul starts with [3.0, 2.0]
this is mul ends with 6.0
a * b = 6.0
this is div starts with [3.0, 2.0]
this is div ends with 1.5
a / b = 1.5





this is add starts with [3.0, 2.0]
this is add ends with 5.0
a + b = 5.0
this is sub starts with [3.0, 2.0]
this is sub ends with 1.0
a - b = 1.0
this is mul starts with [3.0, 2.0]
this is mul ends with 6.0
a * b = 6.0
this is div starts with [3.0, 2.0]
this is div ends with 1.5
a / b = 1.5

 

(5)cglib动态代理
  要使用cglib,需要引入jar包(比如:cglib-2.2.2.jar, asm-3.3.1.jar)。

  引入jar包不对的话,可能会引起下面的问题:
    question1:java.lang.noclassdeffounderror: org/objectweb/asm/type
    answer1:只引入了 cglib-2.2.2.jar, 未引入 asm-3.3.1.jar

    question2:class net.sf.cglib.core.debuggingclasswriter overrides final method visit.
    answer2:引入了 asm-3.3.1.jar, 但是 版本不对,引发冲突。

 

 

 

【实例五:】
核心类:
    calculatorimpl.java              某个类
    calculatorcglibproxy.java        某个类的代理类
    main.java                        测试类
    
【calculatorimpl.java】
package com.company;

/**
 * 计算器类,定义常用方法
 */
public class calculatorimpl {
    public double add(double a, double b) {
        return a + b;
    }

    public double sub(double a, double b) {
        return a - b;
    }

    public double mul(double a, double b) {
        return a * b;
    }

    public double div(double a, double b) {
        if (b == 0) {
            system.out.println("除数不能为0");
            return 0;
        }
        return a / b;
    }
}


【calculatorcglibproxy.java】
package com.company;

import net.sf.cglib.proxy.enhancer;
import net.sf.cglib.proxy.methodinterceptor;
import net.sf.cglib.proxy.methodproxy;

import java.lang.reflect.method;
import java.util.arrays;

/**
 * cglib实现动态代理
 */
public class calculatorcglibproxy implements methodinterceptor{
    private object calculator; // 用于保存代理对象

    calculatorcglibproxy(object calculator) {
        this.calculator = calculator;  // 获取代理的对象
    }

    @override
    public object intercept(object o, method method, object[] objects, methodproxy methodproxy) throws throwable {
        string methodname = method.getname(); // 获取方法名
        system.out.println("this is " + methodname + " starts with " + arrays.aslist(objects));
        object obj = method.invoke(this.calculator, objects);
        system.out.println("this is " + methodname + " ends  with " + obj);
        return obj;
    }

    /**
     * 获取cglib动态代理的对象
     *
     * @return 动态代理的对象
     */
    public object getcglibproxy(){
        // 1.创建cglib的核心类对象
        enhancer enhancer = new enhancer();

        // 2.设置父类
        enhancer.setsuperclass(calculator.getclass());

        // 3.设置回调(类似于jdk动态代理中的invocationhandler对象)
        enhancer.setcallback(this);

        // 4.返回代理对象
        return enhancer.create();
    }
}


【main.java】
package com.company;

import net.sf.cglib.proxy.enhancer;

import java.lang.reflect.proxy;

/**
 * 测试类
 */
public class main {

    public static void main(string[] args) {
        calculatorimpl realcalculator = new calculatorimpl();
        double a = 3.0;
        double b = 2.0;
//        方式一
        calculatorcglibproxy calculatorcglibproxy = new calculatorcglibproxy(realcalculator);
        calculatorimpl calculator = (calculatorimpl) new enhancer().create(realcalculator.getclass(), calculatorcglibproxy);

        system.out.println("a + b = " + calculator.add(a, b));
        system.out.println("a - b = " + calculator.sub(a, b));
        system.out.println("a * b = " + calculator.mul(a, b));
        system.out.println("a / b = " + calculator.div(a, b));

        system.out.println();
        system.out.println();
        system.out.println();
        system.out.println();
        system.out.println();

//        方式二
        calculatorimpl calculator2 = (calculatorimpl) (new calculatorcglibproxy(realcalculator).getcglibproxy());
        system.out.println("a + b = " + calculator2.add(a, b));
        system.out.println("a - b = " + calculator2.sub(a, b));
        system.out.println("a * b = " + calculator2.mul(a, b));
        system.out.println("a / b = " + calculator2.div(a, b));
    }
}


【结果:】
this is add starts with [3.0, 2.0]
this is add ends  with 5.0
a + b = 5.0
this is sub starts with [3.0, 2.0]
this is sub ends  with 1.0
a - b = 1.0
this is mul starts with [3.0, 2.0]
this is mul ends  with 6.0
a * b = 6.0
this is div starts with [3.0, 2.0]
this is div ends  with 1.5
a / b = 1.5





this is add starts with [3.0, 2.0]
this is add ends  with 5.0
a + b = 5.0
this is sub starts with [3.0, 2.0]
this is sub ends  with 1.0
a - b = 1.0
this is mul starts with [3.0, 2.0]
this is mul ends  with 6.0
a * b = 6.0
this is div starts with [3.0, 2.0]
this is div ends  with 1.5
a / b = 1.5

 

三、spring中使用aop

1、切入点表达式

(1)切入点表达式的写法: (基于execution的函数完成的)

execution([访问修饰符] 返回值类型 包路径.类名.方法名(参数))

execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern (param-pattern) throws-pattern?)
其中:(?表示为可选项)
    modifiers-pattern?                修饰符匹配
    ret-type-pattern                  返回值类型
    declaring-type-pattern?           类路径匹配
    name-pattern                      方法名匹配 
    (param-pattern)                   参数匹配
    throws-pattern?                  异常类型匹配
    “*” 表示任意返回值类型
    “..” 表示任意参数
    
【举例:】
全匹配方式:
    execution(public void com.company.calculatorimpl.add(..))

访问修饰符可省略
    execution(void com.company.calculatorimpl.add(..))

可使用*,表示任意返回值
    execution(* com.company.calculatorimpl.add(..))
    
包路径可以使用*,表示任意包. 但是*.的个数要和包的层级数相匹配,可以使用*..,表示当前包,及其子包
    execution(* *.*.calculatorimpl.add(..))
    
类名可以使用*,表示任意类
    execution(* *..*.add(..))
    
方法名可以使用*,表示任意方法
    execution(* *..*.*(..))
    
参数列表可以使用*,表示参数可以是任意数据类型,但是必须存在参数
     execution(* *..*.*(*))
     
参数列表可以使用..表示有无参数均可,有参数可以是任意类型
    execution(* *..*.*(..))
    
全通配方式,可以匹配匹配任意方法
    execution(* *..*.*(..))

 

2、xml版 配置文件的写法、规则

(1)配置 通知类(切面) 与 被通知的类(目标对象)。

 <!-- 配置目标对象,即被增强的对象 -->
<bean id="calculator" class="com.company.calculatorimpl"/>

<!-- 将增强类(切面类)交给spring管理 -->
<bean id="calculatorenhancer" class="com.company.calculatorenhancer"/>

(2)<aop:config>
  用于声明aop配置,所有的aop配置代码均写在其中。

<aop:config>
    <!-- aop配置的代码都写在此处 -->
</aop:config>

(3)<aop:aspect>
  用于配置切面。
  其属性:
    id : 为指定切面的id,
    ref :为引用通知类的 id。

<aop:config>
    <!-- aop配置的代码都写在此处 -->
    <aop:aspect id="calculatoradvice" ref="calculatorenhancer">
        <!--配置通知的类型要写在此处-->
    </aop:aspect>
</aop:config>

(4)<aop:pointcut>
  用于配置切点表达式,用于指定对哪些方法进行增强。
  其属性:
    id:为指定切点表达式的id。
    expression: 指定切入点表达式。

<aop:config>
    <!-- aop配置的代码都写在此处 -->
    
    <!--配置切点表达式-->
     <aop:pointcut id="aspect1" expression="execution(* com.company.calculatorimpl.*(..))"></aop:pointcut>
        
    <!--配置切面,通知的类型要写在此处-->
    <aop:aspect id="calculatoradvice" ref="calculatorenhancer">
          
    </aop:aspect>
</aop:config>

(5)配置通知方法
  <aop:before>: 配置前置通知,指定的增强方法在切入点方法之前执行。
  <aop:after-returning>: 配置后置返回通知,指定的增强方法在切入点方法正常执行之后执行。
  <aop:after-throwing>: 配置后置异常通知,指定的增强方法在切入点方法产生异常后执行。
  <aop:after>: 配置后置通知,无论切入点方法执行时是否发生异常,指定的增强方法都会最后执行。
  <aop:around>: 配置环绕通知,可以在代码中手动控制增强代码的执行时机。
其属性:
  method:用于指定 通知类中的 通知方法名。
  ponitcut-ref:指定切入点的表达式的id。
  poinitcut:指定切入点表达式。

<aop:config>
    <!-- aop配置的代码都写在此处 -->
   <!--配置切点表达式-->
   <aop:pointcut id="aspect1" expression="execution(* com.company.calculatorimpl.*(..))"></aop:pointcut>
         
     <!--配置通知的类型要写在此处-->
    <aop:aspect id="calculatoradvice" ref="calculatorenhancer">
       <!--配置各种类型的通知-->
        <aop:before method="printlogbefore" pointcut-ref="aspect1"></aop:before>
        <aop:after-returning method="printlogafterreturning" pointcut-ref="aspect1"></aop:after-returning>
            <aop:after-throwing method="printlogafterthrowing" pointcut-ref="aspect1"></aop:after-throwing>
        <aop:after method="printlogafter" pointcut-ref="aspect1"></aop:after>
        <!--环绕通知一般单独使用-->       
        <!-- <aop:around method="printlogaround" pointcut-ref="aspect1"></aop:around> -->
     </aop:aspect>
</aop:config>

 

3、xml版

(1)导入junit、aop、spring等相关jar包。

 

 

注:若使用 junit 报错: java.lang.noclassdeffounderror: org/hamcrest/selfdescribing 。
可以导入hamcrest-core-1.3.jar。

 

(2)目录结构

 

 

(3)代码
  注:环绕通知的返回值必须是object,形参必须是proceedingjoingpoint。

【实例六:】
核心类、接口:
    calculator.java            接口
    calculatorimpl.java        接口实现类,被通知类
    calculatorenhancer.java    通知(切面)类,用于定义相关通知方法
    applicationcontext.xml     配置文件,用于 通知类  与  被通知类 关联  
    calculatortest.java        使用junit进行单元测试
    

【calculator.java】
package com.lyh.service;

/**
 * 计算器接口,定义常用方法
 */
public interface calculator {
    /**
     * 加法操作
     * @param a 实数
     * @param b 实数
     * @return 相加结果
     */
    public double add(double a, double b);

    /**
     * 减法操作
     * @param a 实数
     * @param b 实数
     * @return 相减结果
     */
    public double sub(double a, double b);

    /**
     * 乘法操作
     * @param a 实数
     * @param b 实数
     * @return 相乘结果
     */
    public double mul(double a, double b);

    /**
     * 除法操作
     * @param a 实数
     * @param b 实数
     * @return 相除结果
     */
    public int div(int a, int b);
}


【calculatorimpl.java】
package com.lyh.service.impl;

import com.lyh.service.calculator;

/**
 * 计算器实现类,实现常用方法
 */
public class calculatorimpl implements calculator{
    @override
    public double add(double a, double b) {
        return a + b;
    }

    @override
    public double sub(double a, double b) {
        return a - b;
    }

    @override
    public double mul(double a, double b) {
        return a * b;
    }

    @override
    public int div(int a, int b) {
        return a / b;
    }
}


【calculatorenhancer.java】
package com.lyh.enhancer;

import org.aspectj.lang.joinpoint;
import org.aspectj.lang.proceedingjoinpoint;

import java.util.arrays;

/**
 * 定义一个切面类
 */
public class calculatorenhancer {

    /**
     * 前置通知:在方法执行前执行的代码
     * @param joinpoint 切入点
     */
    public void beforeexecute(joinpoint joinpoint){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("beforeexecute");
        system.out.println("this is " + methodname + " starts with " + arrays.aslist(joinpoint.getargs()));
        system.out.println();
    }

    /**
     * 后置通知:在方法执行后执行的代码(无论该方法是否发生异常),注意后置通知拿不到执行的结果
     * @param joinpoint 切入点
     */
    public void afterexecute(joinpoint joinpoint){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("afterexecute");
        system.out.println();
    }

    /**
     * 后置返回通知:在方法正常执行后执行的代码,可以获取到方法的返回值
     * @param joinpoint 切入点
     * @param result 方法执行的结果
     */
    public void afterreturningexecute(joinpoint joinpoint, object result){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("afterreturningexecute");
        system.out.println("this is " + methodname + " ends with " + result);
        system.out.println();
    }

    /**
     * 后置异常通知:在方法抛出异常之后执行,可以访问到异常信息。
     * @param joinpoint 切入点
     * @param exception 异常信息
     */
    public void afterexceptionexecute(joinpoint joinpoint,  exception exception){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("afterexceptionexecute");
        system.out.println("this is " + methodname + " exception with: " + exception);
        system.out.println();
    }

    /**
     * 环绕通知。
     * spring框架为我们提供一个接口proceedingjoinpoint,它的实例对象可以作为环绕通知方法的参数,通过参数控制被增强方法的执行时机。
     * proceedingjoinpoint对象的getargs()方法返回被拦截的参数
     * proceedingjoinpoint对象的proceed()方法执行被拦截的方法
     * @param joinpoint 连接点
     * @return 方法计算的结果值
     */
    public object aroundexecute(proceedingjoinpoint joinpoint){
        object result = null;
        try{
            system.out.println("beforeexecute");
            result = joinpoint.proceed(joinpoint.getargs());
            system.out.println("afterreturningexecute");
        }catch (throwable e){
            system.out.println("afterexceptionexecute");
        }finally {
            system.out.println("afterexecute");
        }
        return result;
    }
}


【applicationcontext.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: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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

        <!-- 配置目标对象,即被增强的对象 -->
        <bean id="calculator" class="com.lyh.service.impl.calculatorimpl"/>

        <!-- 将增强类(切面类)交给spring管理 -->
        <bean id="calculatorenhancer" class="com.lyh.enhancer.calculatorenhancer"/>

        <aop:config>
            <!-- aop配置的代码都写在此处 -->

            <!--配置切点表达式-->
            <aop:pointcut id="beforetest" expression="execution(* com.lyh.service.impl.calculatorimpl.add(..))"></aop:pointcut>
            <aop:pointcut id="aftertest" expression="execution(* com.lyh.service.impl.calculatorimpl.add(..))"></aop:pointcut>
            <aop:pointcut id="afterreturningtest" expression="execution(* com.lyh.service.impl.calculatorimpl.add(..))"></aop:pointcut>
            <aop:pointcut id="afterthrowingtest" expression="execution(* com.lyh.service.impl.calculatorimpl.div(..))"></aop:pointcut>
            <aop:pointcut id="aroundtest" expression="execution(* com.lyh.service.impl.calculatorimpl.sub(..))"></aop:pointcut>


            <!--配置通知的类型要写在此处-->
            <aop:aspect id="calculatoradvice" ref="calculatorenhancer">
                <!--配置各种类型的通知-->
                <aop:before method="beforeexecute" pointcut-ref="beforetest"></aop:before>
                <aop:after method="afterexecute" pointcut-ref="aftertest"></aop:after>
                <aop:after-returning method="afterreturningexecute" pointcut-ref="afterreturningtest" returning="result"></aop:after-returning>
                <aop:after-throwing method="afterexceptionexecute" pointcut-ref="afterthrowingtest" throwing="exception"></aop:after-throwing>
                <aop:around method="aroundexecute" pointcut-ref="aroundtest"></aop:around>
            </aop:aspect>
        </aop:config>

</beans>


【calculatortest.java】
package com.lyh.test;

import com.lyh.service.calculator;
import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.springjunit4classrunner;

import java.math.bigdecimal;

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = {"classpath:applicationcontext.xml"})
public class calculatortest {
    @autowired
    private calculator calculator;

    /**
     * 测试 前置通知,后置通知,后置返回通知
     */
    @test
    public void test(){
        double a = 3.0;
        double b = 2.0;
        system.out.println("a + b = " + calculator.add(a, b));
    }

    /**
     * 测试后置异常通知,
     * 对于除数为0的情况(即b = 0时),
     * 如果二者均为int型(long也是int型),结果会抛出异常:java.lang.arithmeticexception: / by zero。
     * 如果其中有一个为double或者float型,结果则是infinity。
     * 为了测试异常,此处将数据置为int型的。
     */
    @test
    public void test2(){
        int a = 3;
        int b = 0;
        system.out.println("a / b = " + calculator.div(a, b));
    }

    /**
     * 测试环绕通知
     */
    @test
    public void test3(){
        int a = 3;
        int b = 0;
        system.out.println("a / b = " + calculator.sub(a, b));
    }
}


【测试结果:】
【运行test()】
beforeexecute
this is add starts with [3.0, 2.0]

afterreturningexecute
this is add ends with 5.0

afterexecute

a + b = 5.0


【运行test1()】
afterexceptionexecute
this is div exception with: java.lang.arithmeticexception: / by zero


java.lang.arithmeticexception: / by zero

    at com.lyh.service.impl.calculatorimpl.div(calculatorimpl.java:29)
    at sun.reflect.nativemethodaccessorimpl.invoke0(native method)
    at sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)
    at sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)
    at java.lang.reflect.method.invoke(method.java:498)
    at org.springframework.aop.support.aoputils.invokejoinpointusingreflection(aoputils.java:333)
    at org.springframework.aop.framework.reflectivemethodinvocation.invokejoinpoint(reflectivemethodinvocation.java:190)
    at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:157)
    at org.springframework.aop.aspectj.aspectjafterthrowingadvice.invoke(aspectjafterthrowingadvice.java:62)
    at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:179)
    at org.springframework.aop.interceptor.exposeinvocationinterceptor.invoke(exposeinvocationinterceptor.java:92)
    at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:179)
    at org.springframework.aop.framework.jdkdynamicaopproxy.invoke(jdkdynamicaopproxy.java:213)
    at com.sun.proxy.$proxy13.div(unknown source)
    at com.lyh.test.calculatortest.test2(calculatortest.java:39)
    at sun.reflect.nativemethodaccessorimpl.invoke0(native method)
    at sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)
    at sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)
    at java.lang.reflect.method.invoke(method.java:498)
    at org.junit.runners.model.frameworkmethod$1.runreflectivecall(frameworkmethod.java:50)
    at org.junit.internal.runners.model.reflectivecallable.run(reflectivecallable.java:12)
    at org.junit.runners.model.frameworkmethod.invokeexplosively(frameworkmethod.java:47)
    at org.junit.internal.runners.statements.invokemethod.evaluate(invokemethod.java:17)
    at org.springframework.test.context.junit4.statements.runbeforetestmethodcallbacks.evaluate(runbeforetestmethodcallbacks.java:75)
    at org.springframework.test.context.junit4.statements.runaftertestmethodcallbacks.evaluate(runaftertestmethodcallbacks.java:86)
    at org.springframework.test.context.junit4.statements.springrepeat.evaluate(springrepeat.java:84)
    at org.junit.runners.parentrunner.runleaf(parentrunner.java:325)
    at org.springframework.test.context.junit4.springjunit4classrunner.runchild(springjunit4classrunner.java:252)
    at org.springframework.test.context.junit4.springjunit4classrunner.runchild(springjunit4classrunner.java:94)
    at org.junit.runners.parentrunner$3.run(parentrunner.java:290)
    at org.junit.runners.parentrunner$1.schedule(parentrunner.java:71)
    at org.junit.runners.parentrunner.runchildren(parentrunner.java:288)
    at org.junit.runners.parentrunner.access$000(parentrunner.java:58)
    at org.junit.runners.parentrunner$2.evaluate(parentrunner.java:268)
    at org.springframework.test.context.junit4.statements.runbeforetestclasscallbacks.evaluate(runbeforetestclasscallbacks.java:61)
    at org.springframework.test.context.junit4.statements.runaftertestclasscallbacks.evaluate(runaftertestclasscallbacks.java:70)
    at org.junit.runners.parentrunner.run(parentrunner.java:363)
    at org.springframework.test.context.junit4.springjunit4classrunner.run(springjunit4classrunner.java:191)
    at org.junit.runner.junitcore.run(junitcore.java:137)
    at com.intellij.junit4.junit4ideatestrunner.startrunnerwithargs(junit4ideatestrunner.java:68)
    at com.intellij.rt.execution.junit.ideatestrunner$repeater.startrunnerwithargs(ideatestrunner.java:47)
    at com.intellij.rt.execution.junit.junitstarter.preparestreamsandstart(junitstarter.java:242)
    at com.intellij.rt.execution.junit.junitstarter.main(junitstarter.java:70)


【运行test3()】
beforeexecute
afterreturningexecute
afterexecute
a / b = 3.0

注:

  使用xml版的时候,执行的顺序 按照 配置文件中的 顺序执行。

  可能会出现  前置通知  -》  后置通知(最终通知) -》  后置返回通知  的情况。

 

 

  也可能会出现  前置通知  -》  后置返回通知  -》  后置通知(最终通知)  的情况。

 

 

4、注解版

(1)在上例 xml 版的基础上,在 applicationcontext.xml 中 添加 <aop:aspectj-autoproxy /> 用于自动代理,同时在相应的地方添加上注解标记。

(2)代码
  注: 使用 @aspect 后执行顺序是 前置通知,后置通知,后置返回通知,可以用 环绕通知 来解决。

【实例七:】
核心类、接口:
    calculator.java            接口
    calculatorimpl.java        接口实现类,被通知类
    calculatorenhancer.java    通知(切面)类,用于定义相关通知方法
    applicationcontext.xml     配置文件,用于 通知类  与  被通知类 关联  
    calculatortest.java        使用junit进行单元测试


【calculator.java】
package com.lyh.service;

/**
 * 计算器接口,定义常用方法
 */
public interface calculator {
    /**
     * 加法操作
     * @param a 实数
     * @param b 实数
     * @return 相加结果
     */
    public double add(double a, double b);

    /**
     * 减法操作
     * @param a 实数
     * @param b 实数
     * @return 相减结果
     */
    public double sub(double a, double b);

    /**
     * 乘法操作
     * @param a 实数
     * @param b 实数
     * @return 相乘结果
     */
    public double mul(double a, double b);

    /**
     * 除法操作
     * @param a 实数
     * @param b 实数
     * @return 相除结果
     */
    public int div(int a, int b);
}


【calculatorimpl.java】
package com.lyh.service.impl;

import com.lyh.service.calculator;
import org.springframework.stereotype.service;

import javax.xml.ws.servicemode;

/**
 * 计算器实现类,实现常用方法
 */
@service
public class calculatorimpl implements calculator{
    @override
    public double add(double a, double b) {
        return a + b;
    }

    @override
    public double sub(double a, double b) {
        return a - b;
    }

    @override
    public double mul(double a, double b) {
        return a * b;
    }

    @override
    public int div(int a, int b) {
        return a / b;
    }
}


【calculatorenhancer.java】
package com.lyh.enhancer;

import org.aspectj.lang.joinpoint;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.component;

import java.util.arrays;

/**
 * 定义一个切面类
 */
@component
@aspect
public class calculatorenhancer {

    /**
     * 前置通知:在方法执行前执行的代码
     * @param joinpoint 切入点
     */
    @before("execution(* com.lyh.service.impl.calculatorimpl.add(..))")
    public void beforeexecute(joinpoint joinpoint){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("beforeexecute");
        system.out.println("this is " + methodname + " starts with " + arrays.aslist(joinpoint.getargs()));
        system.out.println();
    }

    /**
     * 后置返回通知:在方法正常执行后执行的代码,可以获取到方法的返回值
     * @param joinpoint 切入点
     * @param result 方法执行的结果
     */
    @afterreturning(returning = "result", value = "execution(* com.lyh.service.impl.calculatorimpl.add(..))")
    public void afterreturningexecute(joinpoint joinpoint, object result){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("afterreturningexecute");
        system.out.println("this is " + methodname + " ends with " + result);
        system.out.println();
    }

    /**
     * 后置通知:在方法执行后执行的代码(无论该方法是否发生异常),注意后置通知拿不到执行的结果
     * @param joinpoint 切入点
     */
    @after("execution(* com.lyh.service.impl.calculatorimpl.add(..))")
    public void afterexecute(joinpoint joinpoint){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("afterexecute");
        system.out.println();
    }



    /**
     * 后置异常通知:在方法抛出异常之后执行,可以访问到异常信息。
     * @param joinpoint 切入点
     * @param exception 异常信息
     */
    @afterthrowing(throwing ="exception", value = "execution(* com.lyh.service.impl.calculatorimpl.div(..))")
    public void afterexceptionexecute(joinpoint joinpoint,  exception exception){
        string methodname = joinpoint.getsignature().getname();
        system.out.println("afterexceptionexecute");
        system.out.println("this is " + methodname + " exception with: " + exception);
        system.out.println();
    }

    /**
     * 环绕通知。
     * spring框架为我们提供一个接口proceedingjoinpoint,它的实例对象可以作为环绕通知方法的参数,通过参数控制被增强方法的执行时机。
     * proceedingjoinpoint对象的getargs()方法返回被拦截的参数
     * proceedingjoinpoint对象的proceed()方法执行被拦截的方法
     * @param joinpoint 连接点
     * @return 方法计算的结果值
     */
    @around("execution(* com.lyh.service.impl.calculatorimpl.sub(..))")
    public object aroundexecute(proceedingjoinpoint joinpoint){
        object result = null;
        try{
            system.out.println("beforeexecute");
            result = joinpoint.proceed(joinpoint.getargs());
            system.out.println("afterreturningexecute");
        }catch (throwable e){
            system.out.println("afterexceptionexecute");
        }finally {
            system.out.println("afterexecute");
        }
        return result;
    }
}

【applicationcontext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemalocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">


    <!-- 自动扫描的包 -->
    <context:component-scan base-package="com.lyh"></context:component-scan>

    <!-- 启用aspectj自动代理 -->
    <aop:aspectj-autoproxy />

</beans>



【calculatortest.java】
package com.lyh.test;

import com.lyh.service.calculator;
import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.test.context.contextconfiguration;
import org.springframework.test.context.junit4.springjunit4classrunner;

import java.math.bigdecimal;

@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = {"classpath:applicationcontext.xml"})
public class calculatortest {
    @autowired
    private calculator calculator;

    /**
     * 测试 前置通知,后置通知,后置返回通知
     */
    @test
    public void test(){
        double a = 3.0;
        double b = 2.0;
        system.out.println("a + b = " + calculator.add(a, b));
    }

    /**
     * 测试后置异常通知,
     * 对于除数为0的情况(即b = 0时),
     * 如果二者均为int型(long也是int型),结果会抛出异常:java.lang.arithmeticexception: / by zero。
     * 如果其中有一个为double或者float型,结果则是infinity。
     * 为了测试异常,此处将数据置为int型的。
     */
    @test
    public void test2(){
        int a = 3;
        int b = 0;
        system.out.println("a / b = " + calculator.div(a, b));
    }

    /**
     * 测试环绕通知
     */
    @test
    public void test3(){
        int a = 3;
        int b = 0;
        system.out.println("a / b = " + calculator.sub(a, b));
    }
}


【测试结果:】
【运行test()】
这里可以看到这里的执行顺序是 前置通知,后置通知,后置返回通知

beforeexecute
this is add starts with [3.0, 2.0]

afterexecute

afterreturningexecute
this is add ends with 5.0

a + b = 5.0


【运行test2()】
afterexceptionexecute
this is div exception with: java.lang.arithmeticexception: / by zero


java.lang.arithmeticexception: / by zero

    at com.lyh.service.impl.calculatorimpl.div(calculatorimpl.java:30)
    at sun.reflect.nativemethodaccessorimpl.invoke0(native method)
    at sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)
    at sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)
    at java.lang.reflect.method.invoke(method.java:498)
    at org.springframework.aop.support.aoputils.invokejoinpointusingreflection(aoputils.java:333)
    at org.springframework.aop.framework.reflectivemethodinvocation.invokejoinpoint(reflectivemethodinvocation.java:190)
    at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:157)
    at org.springframework.aop.aspectj.aspectjafterthrowingadvice.invoke(aspectjafterthrowingadvice.java:62)
    at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:179)
    at org.springframework.aop.interceptor.exposeinvocationinterceptor.invoke(exposeinvocationinterceptor.java:92)
    at org.springframework.aop.framework.reflectivemethodinvocation.proceed(reflectivemethodinvocation.java:179)
    at org.springframework.aop.framework.jdkdynamicaopproxy.invoke(jdkdynamicaopproxy.java:213)
    at com.sun.proxy.$proxy20.div(unknown source)
    at com.lyh.test.calculatortest.test2(calculatortest.java:39)
    at sun.reflect.nativemethodaccessorimpl.invoke0(native method)
    at sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62)
    at sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43)
    at java.lang.reflect.method.invoke(method.java:498)
    at org.junit.runners.model.frameworkmethod$1.runreflectivecall(frameworkmethod.java:50)
    at org.junit.internal.runners.model.reflectivecallable.run(reflectivecallable.java:12)
    at org.junit.runners.model.frameworkmethod.invokeexplosively(frameworkmethod.java:47)
    at org.junit.internal.runners.statements.invokemethod.evaluate(invokemethod.java:17)
    at org.springframework.test.context.junit4.statements.runbeforetestmethodcallbacks.evaluate(runbeforetestmethodcallbacks.java:75)
    at org.springframework.test.context.junit4.statements.runaftertestmethodcallbacks.evaluate(runaftertestmethodcallbacks.java:86)
    at org.springframework.test.context.junit4.statements.springrepeat.evaluate(springrepeat.java:84)
    at org.junit.runners.parentrunner.runleaf(parentrunner.java:325)
    at org.springframework.test.context.junit4.springjunit4classrunner.runchild(springjunit4classrunner.java:252)
    at org.springframework.test.context.junit4.springjunit4classrunner.runchild(springjunit4classrunner.java:94)
    at org.junit.runners.parentrunner$3.run(parentrunner.java:290)
    at org.junit.runners.parentrunner$1.schedule(parentrunner.java:71)
    at org.junit.runners.parentrunner.runchildren(parentrunner.java:288)
    at org.junit.runners.parentrunner.access$000(parentrunner.java:58)
    at org.junit.runners.parentrunner$2.evaluate(parentrunner.java:268)
    at org.springframework.test.context.junit4.statements.runbeforetestclasscallbacks.evaluate(runbeforetestclasscallbacks.java:61)
    at org.springframework.test.context.junit4.statements.runaftertestclasscallbacks.evaluate(runaftertestclasscallbacks.java:70)
    at org.junit.runners.parentrunner.run(parentrunner.java:363)
    at org.springframework.test.context.junit4.springjunit4classrunner.run(springjunit4classrunner.java:191)
    at org.junit.runner.junitcore.run(junitcore.java:137)
    at com.intellij.junit4.junit4ideatestrunner.startrunnerwithargs(junit4ideatestrunner.java:68)
    at com.intellij.rt.execution.junit.ideatestrunner$repeater.startrunnerwithargs(ideatestrunner.java:47)
    at com.intellij.rt.execution.junit.junitstarter.preparestreamsandstart(junitstarter.java:242)
    at com.intellij.rt.execution.junit.junitstarter.main(junitstarter.java:70)


【运行test3()】
beforeexecute
afterreturningexecute
afterexecute
a / b = 3.0

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网