Spring框架学习[创建AOP代理对象并对目标对象切面拦截](六)

2014-11-24 03:05:49 · 作者: · 浏览: 7
); if (targetClass == null) { throw new AopConfigException("TargetSource cannot determine target class: " + "Either an interface or a target is required for proxy creation."); } //如果配置的AOP目标类是接口,则使用JDK动态代理机制来生成AOP代理 if (targetClass.isInterface()) { return new JdkDynamicAopProxy(config); } //如果AOP配置的目标类不是接口,则使用CGLIB的方式来生成AOP代理 if (!cglibAvailable) { throw new AopConfigException( "Cannot proxy target class because CGLIB2 is not available. " + "Add CGLIB to the class path or specify proxy interfaces."); } return CglibProxyFactory.createCglibProxy(config); } else { return new JdkDynamicAopProxy(config); } } //判断AOP是否只配置了SpringProxy代理接口或者没有配置任何代理接口 private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) { //获取AOP配置的所有AOP代理接口 Class[] interfaces = config.getProxiedInterfaces(); return (interfaces.length == 0 || (interfaces.length == 1 && SpringProxy.class.equals(interfaces[0]))); } }

通过对DefaultAopProxyFactory的源码分析,我们了解了Spring在创建AOP代理对象时,如果配置的目标类是接口,则使用JDK的动态代理机制来生成AOP代理,如果使用的不是接口,则使用CGLIB方式来生成AOP的动态代理。

4.JDK动态代理机制创建AOPProxy代理对象:

JDK的动态代理机制只能对接口起作用,即如果要对一个对象使用JDK动态代理方式生成代理对象时,该对象必须实现接口,Spring中通过JdkDynamicAopProxy类使用JDK动态代理机制生成AOPProxy代理对象,JdkDynamicAopProxy的主要源码如下:

[java] view plaincopyprint final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable { …… //JdkDynamicAopProxy的构造方法 public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException { Assert.notNull(config, "AdvisedSupport must not be null"); //获取AOPBeanFactory中配置的通知器链和目标源 if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { throw new AopConfigException("No advisors and no TargetSource specified"); } //为当前对象设置AOP配置 this.advised = config; } //获取AOP代理对象的入口方法