一、简介
动态代理的实现方式较常用的方式有两种,用jdk的proxy类实现,必须依赖接口。或者使用cglib的扩展包实现,因为是产生类的子类所以代理的类不能为final类。
二、示例
1、 其中UserServiceImpl 是 UserService的实现
( UserServiceImpl implements UserService )
2、使用JDK的Proxy进行代理
import java.lang.reflect.Proxy;
...
public class JDKProxyTestMain {
public static void main(String[] args) {
UserService proxyUserService = (UserService) Proxy
.newProxyInstance(UserServiceImpl.class.getClassLoader(),
UserServiceImpl.class.getInterfaces(),
new JDKInvocationHandler(new UserServiceImpl()));
proxyUserService.save();
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class JDKInvocationHandler implements InvocationHandler {
private Object targetObject;
public JDKInvocationHandler(Object targetObject) {
this.targetObject = targetObject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("--1---");
Object result = method.invoke(targetObject, args);
System.out.println("--2---");
return result;
}
}
3、使用cglib进行代理实现
import net.sf.cglib.proxy.Enhancer;
...
public class CglibTestMain {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(UserServiceImpl.class);
enhancer.setCallback(new CglibMethodInterceptor(new UserServiceImpl()));
UserServiceImpl userServiceProxy= (UserServiceImpl) enhancer.create();
userServiceProxy.save();
}
}
import java.lang.reflect.Method;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CglibMethodInterceptor implements MethodInterceptor {
private Object targetObj;
public CglibMethodInterceptor(Object targetObj) {
this.targetObj = targetObj;
}
@Override
public Object intercept(Object proxyObj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
System.out.println("---begin---");
Object result = method.invoke(this.targetObj, args);
System.out.println("---end---");
return result;
}
}