1. 程式人生 > >spring aop 預設代理的實現

spring aop 預設代理的實現

spring aop 預設代理實現類為:DefaultAopProxyFactory

一下為部分程式碼片段:

/** Whether the CGLIB2 library is present on the classpath */
	private static final boolean cglibAvailable =
			ClassUtils.isPresent("net.sf.cglib.proxy.Enhancer", DefaultAopProxyFactory.class.getClassLoader());


	public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
		if (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()) {
				return new JdkDynamicAopProxy(config);
			}
			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);
		}
	}

可以看出如果目標類是介面,則用jdk動態代理,否則判斷classpath中是否引入cglib代理,沒有則拋異常,有則用cglib代理

部分關於cglib代理的問題可以參考:http://netfork.iteye.com/blog/286215