Spring 代理的选择
Spring使用ProxyFactory用来创建代理类,用AopProxyFactory选择具体的代理实现,总共有两种实现,一个是JdkDynamicAopProxy,另一个是ObjenesisCglibProxy。代理的选择具体可以分为以下三种情况。
1.proxyTargetClass为false,目标实现了接口,用jdk实现
//4.创建代理Target target = new Target();ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTarget(target);proxyFactory.addAdvisor(advisor);proxyFactory.setInterfaces(target.getClass().getInterfaces());I1 proxy = (I1) proxyFactory.getProxy();System.out.println(proxy.getClass());proxy.foo();System.out.println("___________");proxy.bar();

2.proxyTargetClass为false,目标没有实现接口,用cglib实现
static class Target2 {public void foo() {System.out.println("Target foo");}public void bar() {System.out.println("Target Bar");}}
//4.创建代理Target2 target = new Target2();ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTarget(target);proxyFactory.addAdvisor(advisor);proxyFactory.setInterfaces(target.getClass().getInterfaces());proxyFactory.setProxyTargetClass(false);Target2 proxy = (Target2) proxyFactory.getProxy();System.out.println(proxy.getClass());proxy.foo();System.out.println("___________");proxy.bar();

3.proxyTargetClass为true,总是使用cglib实现
//4.创建代理Target target = new Target();ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTarget(target);proxyFactory.addAdvisor(advisor);proxyFactory.setInterfaces(target.getClass().getInterfaces());proxyFactory.setProxyTargetClass(true);I1 proxy = (I1) proxyFactory.getProxy();System.out.println(proxy.getClass());proxy.foo();System.out.println("___________");proxy.bar();

