本文共 2925 字,大约阅读时间需要 9 分钟。
我是一个梦想家,睡一次马银霜是我的梦想。。。
一:TargetSource是一个接口,该接口全限定名为:org.springframework.aop.TargetSource
假设有个类User,那么我创建一个User的代理,P1
倘若又有个类,Order,那么我需要创建一个Order的代理,P2 倘若…那么…Pn如果在代理类与被代理类之间,加一层叫TargetSource的东西,TargetSource的实现类持有被代理对象的引用,这样,以后不管代理什么,需要替换的只是TargetSource中持有的对象
现有一个普通的java类,名字叫User
public class User { public void test() { System.out.println(this); }}
下面的代码说明了如何使用TargetSource包装一个类,并且为该其生成代理的
User u1=new User ();TargetSource sts=new SingletonTargetSource(u1);User proxy=(User)ProxyFactory.getProxy(sts);// 此处会打印出falseSystem.out.println(u1== proxy);// 此处调用test方法,但是本质上还是调用了u1的方法,// 因为proxy持有target的引用,其实就是proxy里又调用了u1.test方法proxy.test();
二:ProxyFactory
从上面的代码可知ProxyFactory类用来创建代理,很明显getProxy方法是static方法,根据代码规范可知ProxyFactory是一个工具类 ProxyFactory继承了ProxyConfig类,而ProxyConfig的属性proxyTargetClass 是满足我们常说的“如果有接口,则使用JDK代理,如果是单独的一个类,则使用CGLIB代理”条件之一,具体是JDK还是CGLIB,改属性是判断条件之一,不过我个人觉得这个条件只是一个过度,本质上并不是从这里判断的,private boolean proxyTargetClass = false;
ProxyFactory类只是一个工具类,它本质上是被DefaultAopProxyFactory类调用,注:DefaultAopProxyFactory需要的是AdvisedSupport类,而ProxyFactory是AdvisedSupport的子类
二:DefaultAopProxyFactory
下面的代码直接使用该类创建一个代理类import org.springframework.aop.TargetSource;import org.springframework.aop.framework.AopProxy;import org.springframework.aop.framework.DefaultAopProxyFactory;import org.springframework.aop.framework.ProxyFactory;import org.springframework.aop.target.SingletonTargetSource;public static void main(String[] args) { User u1 = new User(); DefaultAopProxyFactory dapf = new DefaultAopProxyFactory(); ProxyFactory proxyFactory = new ProxyFactory(); TargetSource sts = new SingletonTargetSource(u1); proxyFactory.setTargetSource(sts); proxyFactory.setProxyTargetClass(true); AopProxy aopProxy = dapf.createAopProxy(proxyFactory); User proxy = (User) aopProxy.getProxy(); System.out.println(u1 == proxy); proxy.test();}
其中createAopProxy方法如下,从该方法可以看到正是我们常说的“如果该类实现了一个接口,则使用JDK代理,否则使用CGLIB代理”
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable { @Override public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException { if (!NativeDetector.inNativeImage() && (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) { Class targetClass = config.getTargetClass(); if (targetClass == null) { throw new AopConfigException("TargetSource cannot determine target class: " + "Either an interface or a target is required for proxy creation."); } if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) { return new JdkDynamicAopProxy(config); } return new ObjenesisCglibAopProxy(config); } else { return new JdkDynamicAopProxy(config); } } private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) { Class [] ifcs = config.getProxiedInterfaces(); return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0]))); }}
代码至此就没必要在往下深究了,意义不大,也耽误时间
转载地址:http://tthws.baihongyu.com/