spring aop as cglib

大家都知道spring的aop.而底层是用了jdk的动态代理,还有cglib.

一般来说代理接口的话就用jdk的动态代理。而当没有接口的时候就用cglib

jdk的动态代理底层是通过生成一个子类实现目标接口,继承 Proxy类,然后在加上eqs ,tostring,hashcode方法

而cglib及可以代理接口,也可以代理类。底层是通过生成一个子类来继承目标类。然后重写里面的方法。因为是继承,所以fianl的方法是重写不了的,代理不了的。下面来看一下cglib具体的代理是如何实现的。

接口类
package org.tatan.test;


    public interface Worker {
        void doSomeWork(int numOfTimes);
    }
    
目标类
package org.tatan.test;
public class WorkerBean implements Worker {

    public void doSomeWork(int numOfTimes) {
        for (int i = 0; i < numOfTimes; i++) {
            System.out.print("");
        }
    }
}
Advice执行流程
package org.tatan.test;
import java.lang.reflect.Method;

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


public class AroundAdvice implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
     
        Object returnValue = invocation.proceed();

        Method m = invocation.getMethod();
        Object target = invocation.getThis();
        Object[] args = invocation.getArguments();
        System.out.println("Executed method: " + m.getName());
        System.out.println("On object of type: " + target.getClass().getName());
        System.out.println("With arguments:");
        for (int i=0;i<args.length;i++) {
            System.out.println("---->" + args[i]);
        }
        System.out.println();
       
        return returnValue;
    }
}
运行
package org.tatan.test;

import org.springframework.aop.framework.ProxyFactory;

public class AOPExample2 {
    public static void main(String[] args) {
        Worker bean = getWorkerBean();
        bean.doSomeWork(100000000);
    }

    private static Worker getWorkerBean() {
        WorkerBean target = new WorkerBean();
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvice(new AroundAdvice());
        pf.setInterfaces(new Class[]{Worker.class});

        return (Worker) pf.getProxy();
    }
}
如果调用了setInterfaces();就不要cglib了,使用JDK Dynamic Proxies,只是使用JDK Dynamic Proxies程序执行的效率比较低。
使用CGLIB的Frozen效率比标准的CGLIB效率高。
package org.tatan.test;

import org.springframework.aop.framework.ProxyFactory;

public class AOPExample2 {
    public static void main(String[] args) {
        Worker bean = getWorkerBean();
        bean.doSomeWork(100000000);
    }

    private static Worker getWorkerBean() {
        WorkerBean target = new WorkerBean();
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvice(new AroundAdvice());
     //  pf.setInterfaces(new Class[]{Worker.class});
        pf.setFrozen(true);

        return (Worker) pf.getProxy();
    }
}

 

你可能感兴趣的:(spring aop)