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******************"); } }
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(); } }
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