• 动态代理代码测试(jdk和glib)


    jdk动态代理代码编写测试(只针对实现接口的方法)
    package
    com.fh.proxy; public interface UserService { public abstract void add(); }
    package com.fh.proxy;
    
    public class UserServiceImpl implements UserService {
    
        
    
        @Override
        public void add() {
           System.out.println("***************add******************");
        }
    
    }
    View Code
    package com.fh.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class MyInvocationHandler implements InvocationHandler {
        
        private Object target;
    
        public MyInvocationHandler(Object target) {
           this.target = target;
        }
    
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("**********before*************");
            Object result = method.invoke(target, args);
            System.out.println("*********after***************");
            return result;
        }
        
        public Object getProxy() {
            return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), 
                    target.getClass().getInterfaces(), this);
        }
    
    }
    package com.fh.proxy;
    
    import org.junit.Test;
    
    public class ProxyTest {
    
         @Test
         public void tests(){
            UserService user  =  new UserServiceImpl();
            MyInvocationHandler handler = new MyInvocationHandler(user);
            UserService proxy =(UserService) handler.getProxy();
            proxy.add();
        }
    
    }
    View Code
    cglib代理-针对没有实现接口的类进行代理,构建目标类的子类进行处理
    package
    com.fh.proxy; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class EnhancerDemo { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(EnhancerDemo.class); enhancer.setCallback(new MethodInterceptorImpl()); EnhancerDemo demo = (EnhancerDemo) enhancer.create(); demo.test(); System.out.println(demo); } public void test() { System.out.println("EnhancerDemo test()"); } private static class MethodInterceptorImpl implements MethodInterceptor{ @Override public Object intercept(Object arg0, Method method, Object[] arg2, MethodProxy proxy) throws Throwable { System.out.println("before*******"+method); Object result = proxy.invokeSuper(arg0, arg2); System.out.println("after********"+method); return result; } } }

    在spring中动态代理是根据有无实现接口,但是可以强制选择cglib

  • 相关阅读:
    Python使用print打印时,展示内容不换行
    二进制、八进制、十进制和十六进制的相互转化(图解)
    IDEA 配置背景颜色(豆沙绿)
    Linux下脚本文件第一行的作用
    IDEA 注释模板配置
    IDE 常用配置
    Python 运算符
    Python 基础
    Chrome 浏览器快捷键
    正则表达式
  • 原文地址:https://www.cnblogs.com/nihaofenghao/p/9428508.html
Copyright © 2020-2023  润新知