JDK和cglib动态代理代码:
package com.zhangxueliang.demo.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class JDKProxyFactory implements InvocationHandler{
private Object target;
public JDKProxyFactory(Object target){
this.target=target;
}
public Object createProxy(){
ClassLoader classLoader = target.getClass().getClassLoader();
Class<?>[] interfaces = target.getClass().getInterfaces();
return Proxy.newProxyInstance(classLoader, interfaces, this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("增强--日志操作。。。。。。。。。。。");
return method.invoke(target, args);
}
}
package com.zhangxueliang.demo.proxy;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
public class CglibProxyFactory implements MethodInterceptor {
private Object target;
public CglibProxyFactory(Object target){
this.target=target;
}
public Object createProxy(){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("cglib日志操作。。。。。。。。");
return method.invoke(target,args);
}
}
package com.zhangxueliang.demo.proxy;
public class Test {
public static void main(String[] args) {
// testJdkProxy();
UserServiceImpl u = new UserServiceImpl();
CglibProxyFactory c = new CglibProxyFactory(u);
UserServiceImpl us = (UserServiceImpl) c.createProxy();
us.login("0000", "123456");
}
private static void testJdkProxy() {
UserServiceImpl u = new UserServiceImpl();
JDKProxyFactory f = new JDKProxyFactory(u);
IUserService us = (IUserService) f.createProxy();
us.login("1111", "2222");
}
}