JDK动态代理
实例:让中介帮忙买车子和买房子
买车和买房
public interface IBuy {void buyHouse();void buyCar();}
然后实现接口
public class BuyImpl implements IBuy {@Overridepublic void buyHouse() {System.out.println("我要买房");}@Overridepublic void buyCar() {System.out.println("我要买车子");}}
动态代理工厂类:
public class ProxyFactory {/*** 单例模式的*/private ProxyFactory(){ }private static ProxyFactory proxyFactory = new ProxyFactory();public static ProxyFactory getInstance(){return proxyFactory;}/*** Jdk动态代理* @param obj 委托对象* @return 代理对象*/public Object getJdkProxy(Object obj){return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object invoke = null;System.out.println("委托给中介代理");invoke = method.invoke(obj, args);System.out.println("给回扣");return invoke;}});}}
JdkProxy测试类执行:
public class JdkProxy {public static void main(String[] args) {IBuy iBuy = new BuyImpl();IBuy jdkProxy = (IBuy) ProxyFactory.getInstance().getJdkProxy(iBuy);jdkProxy.buyHouse();System.out.println("----------");jdkProxy.buyCar();}}
结果:

Cglib动态代理
pom文件引入依赖
<!--引入cglib依赖--><dependency><groupId>cglib</groupId><artifactId>cglib</artifactId><version>2.1_2</version></dependency>
修改ProxyFactory工厂,添加cglib代理
··················/*** 使用cglib动态代理生成代理对象* @param obj 委托对象* @return*/public Object getCglibProxy(Object obj) {return Enhancer.create(obj.getClass(), new MethodInterceptor() {@Overridepublic Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {Object result = null;System.out.println("委托给中介代理交2000元");result = method.invoke(obj,objects);System.out.println("给回扣两个点");return result;}});}··················
Cglib测试类执行:
public class CglibProxy {public static void main(String[] args) {BuyImpl buy = new BuyImpl(); // 委托对象// 获取rentingHouse对象的代理对象,// Enhancer类似于JDK动态代理中的Proxy// 通过实现接口MethodInterceptor能够对各个方法进行拦截增强,类似于JDK动态代理中的InvocationHandler// 使用工厂来获取代理对象BuyImpl cglibProxy = (BuyImpl) ProxyFactory.getInstance().getCglibProxy(buy);cglibProxy.buyCar();System.out.println("----------");cglibProxy.buyHouse();}}
结果:

注意
JDK动态代理中,我们必须使用接口。而Cglib则不需要。
注意观察上例中两个测试列的区别即可:
JDK IBuy iBuy = new BuyImpl();
Cglib BuyImpl buy = new BuyImpl();
