动态代理

动态代理为我们实现了方法增强功能。java的动态代理主要有jdk自带的动态代理和cglib动态代理。

1、jdk动态代理需要根据接口实现,一个新实现该接口的代理类。

2、cglib动态代理则是直接作用于对象,直接继承原始类,实现增强。

直接上代码

 

 

 1、jdk动态代理使用

package com.example.spring.proxy.jdk;

public interface TargetInterface {
    void test();
}


package com.example.spring.proxy.jdk;

public class TargetClass implements TargetInterface {
    @Override
    public void test() {
        System.out.println("test");
    }
}

package com.example.spring.proxy.jdk;

import java.lang.reflect.Proxy;

public class Test {

    /**
     * jdk 动态代理是基于接口实现一个代理类,从而实现增强
     *
     * @param args
     */
    public static void main(String[] args) {
        TargetClass targetClass = new TargetClass();

        TargetInterface targetInterface = (TargetInterface) Proxy.newProxyInstance(Test.class.getClassLoader(),
                new Class[]{TargetInterface.class},
                (proxy, method, rgs) -> {
                    System.out.println("before");
                    Object object = method.invoke(targetClass, args);
                    System.out.println("after");
                    return object;
                }
        );

        targetInterface.test();
    }
}

 

2、cglib动态代理使用

package com.example.spring.proxy.cglb;

public class TargetClass { public void test() { System.out.println("test"); } } package com.example.spring.proxy.cglb; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class Test { public static void main(String[] args) { TargetClass targetClass = new TargetClass(); Enhancer enhance = new Enhancer(); enhance.setSuperclass(TargetClass.class); enhance.setCallback(new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("before"); Object obj = method.invoke(targetClass, objects); System.out.println("after"); return obj; } }); TargetClass proxy = (TargetClass) enhance.create(); proxy.test(); } }

 

posted @ 2022-10-23 22:58  _wzl  阅读(20)  评论(0编辑  收藏  举报