1、静态代理;
public class HelloProxy implements Hello { private HelloImpl helloImpl; public HelloProxy() { helloImpl = new HelloImpl(); } @Override public void say(String name) { before(); helloImpl.say(name); after(); } private void before() { System.out.println("Before"); } private void after() { System.out.println("After"); }}
2、JDK 动态代理(实现InvocationHandler ):
public class DynamicProxy implements InvocationHandler { private Object target; public DynamicProxy(Object target) { this.target = target; } @Override //实现自己的invoke public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { before(); Object result = method.invoke(target, args); after(); return result; } @SuppressWarnings("unchecked") publicT getProxy() { return (T) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), this ); }public static void main(String[] args) { DynamicProxy dynamicProxy = new DynamicProxy(new HelloImpl()); Hello helloProxy = dynamicProxy.getProxy(); helloProxy.say("Jack");} }
3、cglib动态代理(需要引入cglib类库);
public class CGLibProxy implements MethodInterceptor { private static CGLibProxy instance = new CGLibProxy(); private CGLibProxy() { } public static CGLibProxy getInstance() { return instance; } publicT getProxy(Class cls) { return (T) Enhancer.create(cls, this); } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { before(); Object result = proxy.invokeSuper(obj, args); after(); return result; }public static void main(String[] args) { HelloImpl helloImpl = CGLibProxy.getInstance().getProxy(HelloImpl.class); helloImpl.say("Jack");}}
4、jdk动态代理和cglib动态代理比较:
(1)JDK动态代理只能针对实现了接口的类生成代理;
(2)CGLIB代理是针对类实现代理,对指定类生成一个子类,覆盖所有方法,该类或方法不能是final;
(3)jdk动态代理创建代理实现类时比CGLib要快;
(4)CGLib据说比jdk动态代理运行的快;
(5)被代理的对象是个实现类时,spring使用jdk代理;
(6)被代理的对象不是个实现类,spring使用CGLib;