静态代理、JDK与CGLIB动态代理、AOP+IoC

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

一、为什么需要代理模式

假设需实现一个计算的类Math、完成加、减、乘、除功能,如下所示:

package com.zhangguo.Spring041.aop01;

public class Math {
    //加
    public int add(int n1,int n2){
        int result=n1+n2;
        System.out.println(n1+"+"+n2+"="+result);
        return result;
    }


    //减
    public int sub(int n1,int n2){
        int result=n1-n2;
        System.out.println(n1+"-"+n2+"="+result);
        return result;
    }

    //乘
    public int mut(int n1,int n2){
        int result=n1*n2;
        System.out.println(n1+"X"+n2+"="+result);
        return result;
    }

    //除
    public int div(int n1,int n2){
        int result=n1/n2;
        System.out.println(n1+"/"+n2+"="+result);
        return result;
    }
}

现在需求发生了变化,要求项目中所有的类在执行方法时输出执行耗时。最直接的办法是修改源代码,如下所示:

package com.zhangguo.Spring041.aop01;

import java.util.Random;

public class Math {
    //加
    public int add(int n1,int n2){
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=n1+n2;
        System.out.println(n1+"+"+n2+"="+result);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //减
    public int sub(int n1,int n2){
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=n1-n2;
        System.out.println(n1+"-"+n2+"="+result);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //乘
    public int mut(int n1,int n2){
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=n1*n2;
        System.out.println(n1+"X"+n2+"="+result);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //除
    public int div(int n1,int n2){
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=n1/n2;
        System.out.println(n1+"/"+n2+"="+result);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //模拟延时
    public void lazy()
    {
        try {
            int n=(int)new Random().nextInt(500);
            Thread.sleep(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

测试运行:

package com.zhangguo.Spring041.aop01;

public class Test {

    @org.junit.Test
    public void test01()
    {
        Math math=new Math();
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
}

缺点:

  1. 工作量特别大,如果项目中有多个类,多个方法,则要修改多次。
  2. 违背了设计原则:开闭原则(OCP),对扩展开放,对修改关闭,而为了增加功能把每个方法都修改了,也不便于维护。
  3. 违背了设计原则:单一职责(SRP),每个方法除了要完成自己本身的功能,还要计算耗时、延时;每一个方法引起它变化的原因就有多种。
  4. 违背了设计原则:依赖倒转(DIP),抽象不应该依赖细节,两者都应该依赖抽象。而在Test类中,Test与Math都是细节。

使用静态代理可以解决部分问题。

二、静态代理

  1. 定义抽象主题接口。
package com.zhangguo.Spring041.aop02;

/**
 * 接口
 * 抽象主题
 */
public interface IMath {
    //加
    int add(int n1, int n2);

    //减
    int sub(int n1, int n2);

    //乘
    int mut(int n1, int n2);

    //除
    int div(int n1, int n2);

}
  1. 主题类,算术类,实现抽象接口。
package com.zhangguo.Spring041.aop02;

/**
 * 被代理的目标对象
 *真实主题
 */
public class Math implements IMath {
    //加
    public int add(int n1,int n2){
        int result=n1+n2;
        System.out.println(n1+"+"+n2+"="+result);
        return result;
    }

    //减
    public int sub(int n1,int n2){
        int result=n1-n2;
        System.out.println(n1+"-"+n2+"="+result);
        return result;
    }

    //乘
    public int mut(int n1,int n2){
        int result=n1*n2;
        System.out.println(n1+"X"+n2+"="+result);
        return result;
    }

    //除
    public int div(int n1,int n2){
        int result=n1/n2;
        System.out.println(n1+"/"+n2+"="+result);
        return result;
    }
}
  1. 代理类
package com.zhangguo.Spring041.aop02;

import java.util.Random;

/**
 * 静态代理类
 */
public class MathProxy implements IMath {

    //被代理的对象
    IMath math=new Math();

    //加
    public int add(int n1, int n2) {
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=math.add(n1, n2);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //减法
    public int sub(int n1, int n2) {
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=math.sub(n1, n2);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //乘
    public int mut(int n1, int n2) {
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=math.mut(n1, n2);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //除
    public int div(int n1, int n2) {
        //开始时间
        long start=System.currentTimeMillis();
        lazy();
        int result=math.div(n1, n2);
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);
        return result;
    }

    //模拟延时
    public void lazy()
    {
        try {
            int n=(int)new Random().nextInt(500);
            Thread.sleep(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  1. 测试运行
package com.zhangguo.Spring041.aop02;

public class Test {

    IMath math=new MathProxy();
    @org.junit.Test
    public void test01()
    {
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
}
  1. 小结

    通过静态代理,是否完全解决了上述的4个问题:

    已解决:

    1. 解决了“开闭原则(OCP)”的问题,因为并没有修改Math类,而扩展出了MathProxy类。
    2. 解决了“依赖倒转(DIP)”的问题,通过引入接口。
    3. 解决了“单一职责(SRP)”的问题,Math类不再需要去计算耗时与延时操作,但从某些方面讲MathProxy还是存在该问题。

    未解决:

    1. 如果项目中有多个类,则需要编写多个代理类,工作量大,不好修改,不好维护,不能应对变化。

如果要解决上面的问题,可以使用动态代理。

三、动态代理,使用JDK内置的Proxy实现

只需要一个代理类,而不是针对每个类编写代理类。

在上一个示例中修改代理类MathProxy如下:

package com.zhangguo.Spring041.aop03;

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

/**
 * 动态代理类
 */
public class DynamicProxy implements InvocationHandler {

    //被代理的对象
    Object targetObject;

    /**
     * 获得被代理后的对象
     * @param object 被代理的对象
     * @return 代理后的对象
     */
    public Object getProxyObject(Object object){
        this.targetObject=object;
        return Proxy.newProxyInstance(
                targetObject.getClass().getClassLoader(), //类加载器
                targetObject.getClass().getInterfaces(),  //获得被代理对象的所有接口
                this);  //InvocationHandler对象
        //loader:一个ClassLoader对象,定义了由哪个ClassLoader对象来生成代理对象进行加载
        //interfaces:一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了
        //h:一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上,间接通过invoke来执行
    }


    /**
     * 当用户调用对象中的每个方法时都通过下面的方法执行,方法必须在接口
     * proxy 被代理后的对象
     * method 将要被执行的方法信息(反射)
     * args 执行方法时需要的参数
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //被织入的内容,开始时间
        long start=System.currentTimeMillis();
        lazy();

        //使用反射在目标对象上调用方法并传入参数
        Object result=method.invoke(targetObject, args);

        //被织入的内容,结束时间
        Long span= System.currentTimeMillis()-start;
        System.out.println("共用时:"+span);

        return result;
    }

    //模拟延时
    public void lazy()
    {
        try {
            int n=(int)new Random().nextInt(500);
            Thread.sleep(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

测试运行:

package com.zhangguo.Spring041.aop03;

public class Test {

    //实例化一个MathProxy代理对象
    //通过getProxyObject方法获得被代理后的对象
    IMath math=(IMath)new DynamicProxy().getProxyObject(new Math());
    @org.junit.Test
    public void test01()
    {
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }

    IMessage message=(IMessage) new DynamicProxy().getProxyObject(new Message());
    @org.junit.Test
    public void test02()
    {
        message.message();
    }
}

小结

JDK内置的Proxy动态代理可以在运行时动态生成字节码,而没必要针对每个类编写代理类。中间主要使用到了一个接口InvocationHandler与Proxy.newProxyInstance静态方法,参数说明如下:

使用内置的Proxy实现动态代理有一个问题:被代理的类必须实现接口未实现接口则没办法完成动态代理

如果项目中有些类没有实现接口,则不应该为了实现动态代理而刻意去抽出一些没有实例意义的接口,通过cglib可以解决该问题。

四、动态代理,使用cglib实现

CGLIB(Code Generation Library)是一个开源项目,是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口,通俗说cglib可以在运行时动态生成字节码。

  1. 使用cglib完成动态代理,大概的原理是:cglib继承被代理的类,重写方法,织入通知,动态生成字节码并运行,因为是继承所以final类是没有办法动态代理的。具体实现如下:
package com.zhangguo.Spring041.aop04;

import java.lang.reflect.Method;
import java.util.Random;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

/*
 * 动态代理类
 * 实现了一个方法拦截器接口
 */
public class DynamicProxy implements MethodInterceptor {

    // 被代理对象
    Object targetObject;

    //Generate a new class if necessary and uses the specified callbacks (if any) to create a new object instance. 
    //Uses the no-arg constructor of the superclass.
    //动态生成一个新的类,使用父类的无参构造方法创建一个指定了特定回调的代理实例
    public Object getProxyObject(Object object) {
        this.targetObject = object;
        //增强器,动态代码生成器
        Enhancer enhancer=new Enhancer();
        //回调方法
        enhancer.setCallback(this);
        //设置生成类的父类类型
        enhancer.setSuperclass(targetObject.getClass());
        //动态生成字节码并返回代理对象
        return enhancer.create();
    }

    // 拦截方法
    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        // 被织入的横切内容,开始时间 before
        long start = System.currentTimeMillis();
        lazy();

        // 调用方法
        Object result = methodProxy.invoke(targetObject, args);

        // 被织入的横切内容,结束时间
        Long span = System.currentTimeMillis() - start;
        System.out.println("共用时:" + span);

        return result;
    }

    // 模拟延时
    public void lazy() {
        try {
            int n = (int) new Random().nextInt(500);
            Thread.sleep(n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

测试运行

package com.zhangguo.Spring041.aop04;

public class Test {
    //实例化一个DynamicProxy代理对象
    //通过getProxyObject方法获得被代理后的对象
    Math math=(Math)new DynamicProxy().getProxyObject(new Math());
    @org.junit.Test
    public void test01()
    {
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
    //另一个被代理的对象,不再需要重新编辑代理代码
    Message message=(Message) new DynamicProxy().getProxyObject(new Message());
    @org.junit.Test
    public void test02()
    {
        message.message();
    }
}

小结

使用cglib可以实现动态代理,即使被代理的类没有实现接口,但被代理的类必须不是final类。

五、使用Spring实现AOP

横切关注点:跨越应用程序多个模块的方法或功能。(软件系统,可以看做由一组关注点即业务或功能或方法组成。其中,直接的业务关注点是直切关注点,而为直切关注点服务的,就是横切关注点。)即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。

切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。

通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。

目标(Target):被通知对象。

代理(Proxy):向目标对象应用通知之后创建的对象。

切入点(PointCut):切面通知执行的“地点”的定义。

连接点(JointPoint):与切入点匹配的执行点。

下面示意图:
image

SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
image

  1. 定义通知(Advice)

前置通知

package com.zhangguo.Spring041.aop05;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

/**
 * 前置通知
 */
public class BeforeAdvice implements MethodBeforeAdvice {

    /**
     * method 方法信息
     * args 参数
     * target 被代理的目标对象
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {
        System.out.println("-----------------前置通知-----------------");
    }
}

后置通知:

package com.zhangguo.Spring041.aop05;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

/**
 * 后置通知
 *
 */
public class AfterAdvice implements AfterReturningAdvice {

    /*
     * returnValue 返回值
     * method 被调用的方法
     * args 方法参数
     * target 被代理对象
     */
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
        System.out.println("-----------------后置通知-----------------");
    }

}

环绕通知

package com.zhangguo.Spring041.aop05;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 环绕通知
 * 方法拦截器
 *
 */
public class SurroundAdvice implements MethodInterceptor {

    public Object invoke(MethodInvocation i) throws Throwable {
        //前置横切逻辑
        System.out.println("方法" + i.getMethod() + " 被调用在对象" + i.getThis() + "上,参数 " + i.getArguments());
        //方法调用
        Object ret = i.proceed();
        //后置横切逻辑
        System.out.println("返回值:"+ ret);
        return ret;
    }
}
  1. 创建代理工厂、设置被代理对象、添加通知。
package com.zhangguo.Spring041.aop05;

import org.springframework.aop.framework.ProxyFactory;

public class Test {

    @org.junit.Test
    public void test01()
    {
        //实例化Spring代理工厂
        ProxyFactory factory=new ProxyFactory();
        //设置被代理的对象
        factory.setTarget(new Math());
        //添加通知,横切逻辑
        factory.addAdvice(new BeforeAdvice());
        factory.addAdvice(new AfterAdvice());
        factory.addAdvice(new SurroundAdvice());
        //从代理工厂中获得代理对象
        IMath math=(IMath) factory.getProxy();
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
    @org.junit.Test
    public void test02()
    {
        //message.message();
    }
}
  1. 封装代理创建逻辑

    在上面的示例中如果要代理不同的对象需要反复创建ProxyFactory对象,代码会冗余。同样以实现方法耗时为示例代码如下:

    1. 创建一个环绕通知:
    package com.zhangguo.Spring041.aop05;
    
    import java.util.Random;
    
    import org.aopalliance.intercept.MethodInterceptor;
    import org.aopalliance.intercept.MethodInvocation;
    
    /**
     * 用于完成计算方法执行时长的环绕通知
     */
    public class TimeSpanAdvice implements MethodInterceptor {
    
        public Object invoke(MethodInvocation invocation) throws Throwable {
            // 被织入的横切内容,开始时间 before
            long start = System.currentTimeMillis();
            lazy();
    
            //方法调用
            Object result = invocation.proceed();
    
            // 被织入的横切内容,结束时间
            Long span = System.currentTimeMillis() - start;
            System.out.println("共用时:" + span);
    
            return result;
        }
    
        // 模拟延时
        public void lazy() {
            try {
                int n = (int) new Random().nextInt(500);
                Thread.sleep(n);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    1. 封装动态代理类
    package com.zhangguo.Spring041.aop05;
    
    import org.springframework.aop.framework.ProxyFactory;
    
    /**
     * 动态代理类
     *
     */
    public abstract class DynamicProxy {
        /**
         * 获得代理对象
         * @param object 被代理的对象
         * @return 代理对象
         */
        public static Object getProxy(Object object){
            //实例化Spring代理工厂
            ProxyFactory factory=new ProxyFactory();
            //设置被代理的对象
            factory.setTarget(object);
            //添加通知,横切逻辑
            factory.addAdvice(new TimeSpanAdvice());
            return factory.getProxy();
        }
    }
    1. 测试运行
    package com.zhangguo.Spring041.aop05;
    
    import org.springframework.aop.framework.ProxyFactory;
    
    public class Test {
    
        @org.junit.Test
        public void test01()
        {
            //从代理工厂中获得代理对象
            IMath math=(IMath) DynamicProxy.getProxy(new Math());
            int n1=100,n2=5;
            math.add(n1, n2);
            math.sub(n1, n2);
            math.mut(n1, n2);
            math.div(n1, n2);
        }
        @org.junit.Test
        public void test02()
        {
            IMessage message=(IMessage) DynamicProxy.getProxy(new Message());
            message.message();
        }
    }

封装动态代理类:

package spring_aop_26;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ProxyFactory;

public class SpringProxy<T> implements MethodInterceptor {

    /**获得代理后的对象*/
    public T getProxyObject(Object target){
        //代理工厂
        ProxyFactory proxy=new ProxyFactory();
        //添加被代理的对象
        proxy.setTarget(target);
        //添加环绕通知
        proxy.addAdvice(this);
        //获得代理后的对象
        return (T) proxy.getProxy();
    }

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        before();
        //调用方法获得结果
        Object result=methodInvocation.proceed();
        after(result);
        return result;
    }

    public void before(){
        System.out.println("调用方法前");
    }
    public void after(Object result){
        System.out.println("调用方法后"+result);
    }
}

六、使用IOC配置的方式实现AOP

引入Spring IOC的核心jar包,方法与前面相同。

创建IOC的配置文件beans.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 被代理的目标对象 -->
    <bean id="target" class="com.zhangguo.Spring041.aop06.Math"></bean>
    <!--通知、横切逻辑-->
    <bean id="advice" class="com.zhangguo.Spring041.aop06.AfterAdvice"></bean>
    <!--代理对象 -->
    <!--interceptorNames 通知数组 -->
    <!--p:target-ref 被代理的对象-->
    <!--p:proxyTargetClass 被代理对象是否为一个类,如果是则使用cglib,否则使用jdk动态代理  -->
    <bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean"
        p:interceptorNames="advice"
        p:target-ref="target"
        p:proxyTargetClass="true"></bean>
</beans>

获得代理类的实例并测试运行

package com.zhangguo.Spring041.aop06;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    @org.junit.Test
    public void test01()
    {
        //容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
        //从代理工厂中获得代理对象
        IMath math=(IMath)ctx.getBean("proxy");
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
}

小结

这里有个值得注意的问题:从容器中获得proxy对象时应该是org.springframework.aop.framework.ProxyFactoryBean类型的对象(如下代码所示),但这里直接就转换成IMath类型了,这是因为:ProxyFactoryBean本质上是一个用来生产Proxy的FactoryBean。如果容器中的某个对象持有某个FactoryBean的引用它取得的不是FactoryBean本身而是 FactoryBean的getObject()方法所返回的对象。所以如果容器中某个对象依赖于ProxyFactoryBean那么它将会使用到 ProxyFactoryBean的getObject()方法所返回的代理对象这就是ProxyFactryBean得以在容器中使用的原因。

七、使用XML配置Spring AOP切面

添加引用,需要引用一个新的jar包:aspectjweaver,该包是AspectJ的组成部分。可以去http://search.maven.org搜索后下载或直接在maven项目中添加依赖。

  1. 定义通知

该通知不再需要实现任何接口或继承抽象类,一个普通的bean即可,方法可以带一个JoinPoint连接点参数,用于获得连接点信息,如方法名,参数,代理对象等。

package com.zhangguo.Spring041.aop08;

import org.aspectj.lang.JoinPoint;

/**
 * 通知
 */
public class Advices {
    //前置通知
    public void before(JoinPoint jp)
    {
        System.out.println("--------------------bofore--------------------");
        System.out.println("方法名:"+jp.getSignature()+",参数:"+jp.getArgs().length+",代理对象:"+jp.getTarget());
    }
    //后置通知
    public void after(JoinPoint jp){
        System.out.println("--------------------after--------------------");
    }
}

通知的类型有多种,有些参数会不一样,特别是环绕通知,通知类型如下:

//前置通知
public void beforeMethod(JoinPoint joinPoint)

//后置通知
public void afterMethod(JoinPoint joinPoint)

//返回值通知
public void afterReturning(JoinPoint joinPoint, Object result)

//抛出异常通知
//在方法出现异常时会执行的代码可以访问到异常对象,可以指定在出现特定异常时在执行通知代码
public void afterThrowing(JoinPoint joinPoint, Exception ex)

//环绕通知
//环绕通知需要携带ProceedingJoinPoint类型的参数
//环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法。
//而且环绕通知必须有返回值,返回值即为目标方法的返回值
public Object aroundMethod(ProceedingJoinPoint pjd)

配置IOC容器依赖的XML文件beansOfAOP.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: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-4.3.xsd">

    <!--被代理的目标对象 -->
    <bean id="math" class="com.zhangguo.Spring041.aop08.Math"></bean>
    <!-- 通知 -->
    <bean id="advice" class="com.zhangguo.Spring041.aop08.Advices"></bean>
    <!-- AOP配置 -->
    <!-- proxy-target-class属性表示被代理的类是否为一个没有实现接口的类,Spring会依据实现了接口则使用JDK内置的动态代理,如果未实现接口则使用cblib -->
    <aop:config proxy-target-class="true">
        <!-- 切面配置 -->
        <!--ref表示通知对象的引用 -->
        <aop:aspect ref="advice">
            <!-- 配置切入点(横切逻辑将注入的精确位置) -->
            <aop:pointcut expression="execution(* com.zhangguo.Spring041.aop08.Math.*(..))" id="pointcut1"/>
            <!--声明通知,method指定通知类型,pointcut指定切点,就是该通知应该注入那些方法中 -->
            <aop:before method="before" pointcut-ref="pointcut1"/>
            <aop:after method="after" pointcut-ref="pointcut1"/>
        </aop:aspect>
    </aop:config>
</beans>

加粗部分的内容是在原IOC内容中新增的,主要是为AOP服务,如果引入失败则没有智能提示。xmlns:是xml namespace的简写。xmlns:xsi:其xsd文件是xml需要遵守的规范,通过URL可以看到,是w3的统一规范,后面通过xsi:schemaLocation来定位所有的解析文件,这里只能成偶数对出现。

<bean id="advice" class="com.zhangguo.Spring041.aop08.Advices"></bean>表示通知bean,也就是横切逻辑bean。<aop:config proxy-target-class="true">用于AOP配置,proxy-target-class属性表示被代理的类是否为一个没有实现接口的类,Spring会依据实现了接口则使用JDK内置的动态代理,如果未实现接口则使用cblib;在Bean配置文件中,所有的Spring AOP配置都必须定义在元素内部。对于每个切面而言,都要创建一个元素来为具体的切面实现引用后端Bean实例。因此,切面Bean必须有一个标识符,供元素引用。

aop:aspect表示切面配置, ref表示通知对象的引用;aop:pointcut是配置切入点,就是横切逻辑将注入的精确位置,那些包,类,方法需要拦截注入横切逻辑。

aop:before用于声明通知,method指定通知类型,pointcut指定切点,就是该通知应该注入那些方法中。在aop Schema中,每种通知类型都对应一个特定地XML元素。通知元素需要pointcut-ref属性来引用切入点,或者用pointcut属性直接嵌入切入点表达式。method属性指定切面类中通知方法的名称。有如下几种:

<!-- 前置通知 -->
<aop:before method="before" pointcut-ref="pointcut1"/>
<!-- 后置通知 -->
<aop:after method="after" pointcut-ref="pointcut1"/>
<!--环绕通知 -->
<aop:around method="around" pointcut="execution(* com.zhangguo.Spring041.aop08.Math.s*(..))"/>
<!--异常通知 -->
<aop:after-throwing method="afterThrowing" pointcut="execution(* com.zhangguo.Spring041.aop08.Math.d*(..))"  throwing="exp"/>
<!-- 返回值通知 -->
<aop:after-returning method="afterReturning" pointcut="execution(* com.zhangguo.Spring041.aop08.Math.m*(..))" returning="result"/>

获得代理对象

package com.zhangguo.Spring041.aop08;

import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    @org.junit.Test
    public void test01()
    {
        //容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beansOfAOP.xml");
        //从代理工厂中获得代理对象
        IMath math=(IMath)ctx.getBean("math");
        int n1=100,n2=5;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
}

环绕通知、异常后通知、返回结果后通知

在配置中我们发现共有5种类型的通知,前面我们试过了前置通知与后置通知,另外几种类型的通知如下代码所示:

package com.zhangguo.Spring041.aop08;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

/**
 * 通知
 */
public class Advices {
    //前置通知
    public void before(JoinPoint jp)
    {
        System.out.println("--------------------前置通知--------------------");
        System.out.println("方法名:"+jp.getSignature().getName()+",参数:"+jp.getArgs().length+",被代理对象:"+jp.getTarget().getClass().getName());
    }
    //后置通知
    public void after(JoinPoint jp){
        System.out.println("--------------------后置通知--------------------");
    }
    //环绕通知
    public Object around(ProceedingJoinPoint pjd) throws Throwable{
        System.out.println("--------------------环绕开始--------------------");
        Object object=pjd.proceed();
        System.out.println("--------------------环绕结束--------------------");
        return object;
    }
    //异常后通知
    public void afterThrowing(JoinPoint jp,Exception exp)
    {
        System.out.println("--------------------异常后通知,发生了异常:"+exp.getMessage()+"--------------------");
    }
    //返回结果后通知
    public void afterReturning(JoinPoint joinPoint, Object result)
    {
        System.out.println("--------------------返回结果后通知--------------------");
        System.out.println("结果是:"+result);
    }
}

容器配置文件beansOfAOP.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: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-4.3.xsd">

    <!--被代理的目标对象 -->
    <bean id="math" class="com.zhangguo.Spring041.aop08.Math"></bean>
    <!-- 通知 -->
    <bean id="advice" class="com.zhangguo.Spring041.aop08.Advices"></bean>
    <!-- AOP配置 -->
    <!-- proxy-target-class属性表示被代理的类是否为一个没有实现接口的类,Spring会依据实现了接口则使用JDK内置的动态代理,如果未实现接口则使用cblib -->
    <aop:config proxy-target-class="true">
        <!-- 切面配置 -->
        <!--ref表示通知对象的引用 -->
        <aop:aspect ref="advice">
            <!-- 配置切入点(横切逻辑将注入的精确位置) -->
            <aop:pointcut expression="execution(* com.zhangguo.Spring041.aop08.Math.a*(..))" id="pointcut1"/>
            <!--声明通知,method指定通知类型,pointcut指定切点,就是该通知应该注入那些方法中 -->
            <aop:before method="before" pointcut-ref="pointcut1"/>
            <aop:after method="after" pointcut-ref="pointcut1"/>
            <aop:around method="around" pointcut="execution(* com.zhangguo.Spring041.aop08.Math.s*(..))"/>
            <aop:after-throwing method="afterThrowing" pointcut="execution(* com.zhangguo.Spring041.aop08.Math.d*(..))"  throwing="exp"/>
            <aop:after-returning method="afterReturning" pointcut="execution(* com.zhangguo.Spring041.aop08.Math.m*(..))" returning="result"/>
        </aop:aspect>
    </aop:config>
</beans>

测试代码:

package com.zhangguo.Spring041.aop08;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    @org.junit.Test
    public void test01()
    {
        //容器
        ApplicationContext ctx=new ClassPathXmlApplicationContext("beansOfAOP.xml");
        //从代理工厂中获得代理对象
        IMath math=(IMath)ctx.getBean("math");
        int n1=100,n2=0;
        math.add(n1, n2);
        math.sub(n1, n2);
        math.mut(n1, n2);
        math.div(n1, n2);
    }
}

小结:不同类型的通知参数可能不相同;aop:after-throwing需要指定通知中参数的名称throwing=”exp”,则方法中定义应该是这样:afterThrowing(JoinPoint jp,Exception exp);aop:after-returning同样需要设置returning指定方法参数的名称。通过配置切面的方法使AOP变得更加灵活。

猜你喜欢

转载自blog.csdn.net/u013276888/article/details/80700487
今日推荐