1. 程式人生 > >動態代理與cglib

動態代理與cglib

art jdk動態代理 super tint pri out eth 通過 ble

代理分為靜態代理,jdk動態代理和cglib

1、首先,說一下靜態代理。

定義一個接口

  

public interface Interface{
    void doSomething();

    void doSomething(String arg);
}

定義一個被代理類,並實現接口

public class RealInterface implements Interface {

    @Override
    public void doSomething() {
        System.out.println("doSomething");
    }

    @Override
    
public void doSomething(String arg) { System.out.println("doSomething " + arg); } }

定義一個代理類,並實現接口

public class SimpleProxy implements Interface {

    private Interface inter;

    public SimpleProxy(Interface inter) {
        this.inter = inter;
    }

    @Override
    public void
doSomething() { System.out.println("proxy start"); inter.doSomething(); } @Override public void doSomething(String arg) { System.out.println("proxy else start"); inter.doSomething(arg); } }

動態代理 ,動態代理需要實現InvocationHandler接口

public class DynamicProxy implements
InvocationHandler { private Object anInterface; public DynamicProxy(Object anInterface) { this.anInterface = anInterface; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("dynamic proxy"); return method.invoke(anInterface,args); } }

cglib,cglib不需要實現接口,通過繼承被代理類來實現代理,類似於Spring AOP,由於是繼承,不能代理final修飾的類

首先,使用maven引入jar包,通過使用

Enhancer 來實現代理。

 <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.6</version>
        </dependency>

/**
 * 靜態代理
 * 動態代理
 * cglib
 */
public class Main {

    public void doSomthing() {
        System.out.println("cglib doSomething");
    }

    public static void consumer(Interface inter) {
        inter.doSomething();
        inter.doSomething("play");
    }

    public static void main(String[] args) {
        /**
         * 靜態代理
         */
        consumer(new RealInterface());
        consumer(new SimpleProxy(new RealInterface()));

        /**
         * 動態代理
         */
        Interface realInterface = new RealInterface();
        Interface anInterface = (Interface)Proxy.newProxyInstance(realInterface.getClass().getClassLoader(),  //Intergace.class.getClassLoader(),
                realInterface.getClass().getInterfaces(), //new class[] {Interface.class},
                new DynamicProxy(realInterface));
        consumer(anInterface);

        /**
         * cglib
         */
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Main.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("cdlib proxy");
                return methodProxy.invokeSuper(o,args);
            }
        });
        Main main = (Main)enhancer.create();
        main.doSomthing();
    }
}

動態代理與cglib