Spring中AOP的學習

1、cglib的學習,cglib是靠繼承關係來實現代理的目的,即具體代碼如下:

Java代碼 複製代碼
  1.  public class AOPInstrumenter implements MethodInterceptor {   
  2.     private static Log logger = LogFactory.getLog(AOPInstrumenter.class);   
  3.     private Enhancer enhancer = new Enhancer();   
  4.     public Object getInstrumentedClass(Class clz) {   
  5.         enhancer.setSuperclass(clz);   
  6.         enhancer.setCallback(this);   
  7.         return enhancer.create();   
  8.     }   
  9.     public Object intercept(Object o, Method method, Object[] methodParameters,MethodProxy methodProxy) throws Throwable {   
  10.         logger.debug("Before Method =>" + method.getName());   
  11.         Object result = methodProxy.invokeSuper(o, methodParameters);   
  12.         logger.debug("After Method =>" + method.getName());   
  13.         return result;   
  14.     }   
  15. }  
 public class AOPInstrumenter implements MethodInterceptor {
	private static Log logger = LogFactory.getLog(AOPInstrumenter.class);
	private Enhancer enhancer = new Enhancer();
	public Object getInstrumentedClass(Class clz) {
		enhancer.setSuperclass(clz);
		enhancer.setCallback(this);
		return enhancer.create();
	}
	public Object intercept(Object o, Method method, Object[] methodParameters,MethodProxy methodProxy) throws Throwable {
		logger.debug("Before Method =>" + method.getName());
		Object result = methodProxy.invokeSuper(o, methodParameters);
		logger.debug("After Method =>" + method.getName());
		return result;
	}
}





2、proxy代理,主要靠實現接口來實現代理的目的,即具體代碼如下:

Java代碼 複製代碼
  1. public class AOPHandler implements InvocationHandler {   
  2.     private static Log logger = LogFactory.getLog(AOPHandler.class);   
  3.     private List interceptors = null;   
  4.     private Object originalObject;   
  5.     /**  
  6.      * 返回動態代理實例  
  7.      *   
  8.      * @param obj  
  9.      * @return  
  10.      */  
  11.     public Object bind(Object obj) {   
  12.         this.originalObject = obj;   
  13.         return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);   
  14.     }   
  15.     /**  
  16.      * 在Invoke方法中,加載對應的Interceptor,並進行  
  17.      * 預處理(before)、後處理(after)以及異常處理(exceptionThrow)過程  
  18.      */  
  19.     public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {   
  20.         Object result = null;   
  21.         Throwable ex = null;   
  22.         InvocationInfo invInfo = new InvocationInfo(proxy, method, args,result, ex);   
  23.         logger.debug("Invoking Before Intercetpors!");   
  24.         invokeInterceptorsBefore(invInfo);   
  25.         try {   
  26.             logger.debug("Invoking Proxy Method!");   
  27.             result = method.invoke(originalObject, args);   
  28.             invInfo.setResult(result);   
  29.             logger.debug("Invoking After Method!");   
  30.             invokeInterceptorsAfter(invInfo);   
  31.         } catch (Throwable tr) {   
  32.             invInfo.setException(tr);   
  33.             logger.debug("Invoking exceptionThrow Method!");   
  34.             invokeInterceptorsExceptionThrow(invInfo);   
  35.             throw new AOPRuntimeException(tr);   
  36.         }   
  37.         return result;   
  38.     }   
  39.     /**  
  40.      * 加載Interceptor  
  41.      *   
  42.      * @return  
  43.      */  
  44.     private synchronized List getIntercetors() {   
  45.         if (null == interceptors) {   
  46.             interceptors = new ArrayList();   
  47.             //Todo:讀取配置,加載Interceptor實例   
  48.             interceptors.add(new MyInterceptor());   
  49.         }   
  50.         return interceptors;   
  51.     }   
  52.     /**  
  53.      * 執行預處理方法  
  54.      *   
  55.      * @param invInfo  
  56.      */  
  57.     private void invokeInterceptorsBefore(InvocationInfo invInfo) {   
  58.         List interceptors = getIntercetors();   
  59.         int len = interceptors.size();   
  60.         for (int i = 0; i < len; i++) {   
  61.             ((Interceptor) interceptors.get(i)).before(invInfo);   
  62.         }   
  63.     }   
  64.     /**  
  65.      * 執行後處理方法  
  66.      *   
  67.      * @param invInfo  
  68.      */  
  69.     private void invokeInterceptorsAfter(InvocationInfo invInfo) {   
  70.         List interceptors = getIntercetors();   
  71.         int len = interceptors.size();   
  72.         for (int i = len - 1; i >= 0; i--) {   
  73.             ((Interceptor) interceptors.get(i)).after(invInfo);   
  74.         }   
  75.     }   
  76.     /**  
  77.      * 執行異常處理方法  
  78.      *   
  79.      * @param invInfo  
  80.      */  
  81.     private void invokeInterceptorsExceptionThrow(InvocationInfo invInfo) {   
  82.         List interceptors = getIntercetors();   
  83.         int len = interceptors.size();   
  84.         for (int i = len - 1; i >= 0; i--) {   
  85.             ((Interceptor) interceptors.get(i)).exceptionThrow(invInfo);   
  86.         }   
  87.     }   
  88. }  
public class AOPHandler implements InvocationHandler {
	private static Log logger = LogFactory.getLog(AOPHandler.class);
	private List interceptors = null;
	private Object originalObject;
	/**
	 * 返回動態代理實例
	 * 
	 * @param obj
	 * @return
	 */
	public Object bind(Object obj) {
		this.originalObject = obj;
		return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this);
	}
	/**
	 * 在Invoke方法中,加載對應的Interceptor,並進行
	 * 預處理(before)、後處理(after)以及異常處理(exceptionThrow)過程
	 */
	public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {
		Object result = null;
		Throwable ex = null;
		InvocationInfo invInfo = new InvocationInfo(proxy, method, args,result, ex);
		logger.debug("Invoking Before Intercetpors!");
		invokeInterceptorsBefore(invInfo);
		try {
			logger.debug("Invoking Proxy Method!");
			result = method.invoke(originalObject, args);
			invInfo.setResult(result);
			logger.debug("Invoking After Method!");
			invokeInterceptorsAfter(invInfo);
		} catch (Throwable tr) {
			invInfo.setException(tr);
			logger.debug("Invoking exceptionThrow Method!");
			invokeInterceptorsExceptionThrow(invInfo);
			throw new AOPRuntimeException(tr);
		}
		return result;
	}
	/**
	 * 加載Interceptor
	 * 
	 * @return
	 */
	private synchronized List getIntercetors() {
		if (null == interceptors) {
			interceptors = new ArrayList();
			//Todo:讀取配置,加載Interceptor實例
			interceptors.add(new MyInterceptor());
		}
		return interceptors;
	}
	/**
	 * 執行預處理方法
	 * 
	 * @param invInfo
	 */
	private void invokeInterceptorsBefore(InvocationInfo invInfo) {
		List interceptors = getIntercetors();
		int len = interceptors.size();
		for (int i = 0; i < len; i++) {
			((Interceptor) interceptors.get(i)).before(invInfo);
		}
	}
	/**
	 * 執行後處理方法
	 * 
	 * @param invInfo
	 */
	private void invokeInterceptorsAfter(InvocationInfo invInfo) {
		List interceptors = getIntercetors();
		int len = interceptors.size();
		for (int i = len - 1; i >= 0; i--) {
			((Interceptor) interceptors.get(i)).after(invInfo);
		}
	}
	/**
	 * 執行異常處理方法
	 * 
	 * @param invInfo
	 */
	private void invokeInterceptorsExceptionThrow(InvocationInfo invInfo) {
		List interceptors = getIntercetors();
		int len = interceptors.size();
		for (int i = len - 1; i >= 0; i--) {
			((Interceptor) interceptors.get(i)).exceptionThrow(invInfo);
		}
	}
}




Java代碼 複製代碼
  1. public class AOPFactory {   
  2.     static AOPHandler txHandler ;   
  3.     private static Log logger = LogFactory.getLog(AOPFactory.class);   
  4.     /**  
  5.      * 根據類名創建類實例  
  6.      *   
  7.      * @param clzName  
  8.      * @return  
  9.      * @throws ClassNotFoundException  
  10.      */  
  11.     public static Object getClassInstance(String clzName) {   
  12.         Class cls;   
  13.         try {   
  14.             cls = Class.forName(clzName);   
  15.             return (Object) cls.newInstance();   
  16.         } catch (ClassNotFoundException e) {   
  17.             logger.debug(e);   
  18.             throw new AOPRuntimeException(e);   
  19.         } catch (InstantiationException e) {   
  20.             logger.debug(e);   
  21.             throw new AOPRuntimeException(e);   
  22.         } catch (IllegalAccessException e) {   
  23.             logger.debug(e);   
  24.             throw new AOPRuntimeException(e);   
  25.         }   
  26.     }   
  27.     /**  
  28.      * 根據傳入的類名,返回AOP代理對象  
  29.      *   
  30.      * @param clzName  
  31.      * @return  
  32.      */  
  33.     public static Object getAOPProxyedObject(String clzName) {   
  34.         txHandler = new AOPHandler();   
  35.         Object obj = getClassInstance(clzName);   
  36.         return txHandler.bind(obj);   
  37.     }   
  38.   
  39.     /**  
  40.      * @return Returns the txHandler.  
  41.      */  
  42.     public static AOPHandler getTxHandler() {   
  43.         return txHandler;   
  44.     }   
  45. }  
public class AOPFactory {
	static AOPHandler txHandler ;
	private static Log logger = LogFactory.getLog(AOPFactory.class);
	/**
	 * 根據類名創建類實例
	 * 
	 * @param clzName
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static Object getClassInstance(String clzName) {
		Class cls;
		try {
			cls = Class.forName(clzName);
			return (Object) cls.newInstance();
		} catch (ClassNotFoundException e) {
			logger.debug(e);
			throw new AOPRuntimeException(e);
		} catch (InstantiationException e) {
			logger.debug(e);
			throw new AOPRuntimeException(e);
		} catch (IllegalAccessException e) {
			logger.debug(e);
			throw new AOPRuntimeException(e);
		}
	}
	/**
	 * 根據傳入的類名,返回AOP代理對象
	 * 
	 * @param clzName
	 * @return
	 */
	public static Object getAOPProxyedObject(String clzName) {
		txHandler = new AOPHandler();
		Object obj = getClassInstance(clzName);
		return txHandler.bind(obj);
	}

	/**
	 * @return Returns the txHandler.
	 */
	public static AOPHandler getTxHandler() {
		return txHandler;
	}
}



Java代碼 複製代碼
  1. public interface Interceptor {   
  2.     public void before(InvocationInfo invInfo);   
  3.     public void after(InvocationInfo invInfo);   
  4.     public void exceptionThrow(InvocationInfo invInfo);   
  5. }  
public interface Interceptor {
	public void before(InvocationInfo invInfo);
	public void after(InvocationInfo invInfo);
	public void exceptionThrow(InvocationInfo invInfo);
}


Java代碼 複製代碼
  1. public class MyInterceptor implements Interceptor {   
  2.     private static Log logger = LogFactory.getLog(MyInterceptor.class);   
  3.     public void before(InvocationInfo invInfo) {   
  4.         logger.debug("Pre-processing");   
  5.     }   
  6.     public void after(InvocationInfo invInfo) {   
  7.         logger.debug("Post-processing");   
  8.     }   
  9.     public void exceptionThrow(InvocationInfo invInfo) {   
  10.         logger.debug("Exception-processing");   
  11.     }   
  12. }  
public class MyInterceptor implements Interceptor {
	private static Log logger = LogFactory.getLog(MyInterceptor.class);
	public void before(InvocationInfo invInfo) {
		logger.debug("Pre-processing");
	}
	public void after(InvocationInfo invInfo) {
		logger.debug("Post-processing");
	}
	public void exceptionThrow(InvocationInfo invInfo) {
		logger.debug("Exception-processing");
	}
}







3、Spring中AOP的實現。剖析Spring中的cglig和proxy。
Spring中的核心模塊爲:bean和aop;其中bean模塊對aop提供了支持。

Java代碼 複製代碼
  1. public abstract class AbstractBeanFactory implements ConfigurableBeanFactory {   
  2. public Object getBean(String name, Class requiredType, Object[] args) throws BeansException {   
  3.         String beanName = transformedBeanName(name);   
  4.         Object bean = null;   
  5.   
  6.         // Eagerly check singleton cache for manually registered singletons.   
  7.         Object sharedInstance = null;   
  8.         synchronized (this.singletonCache) {   
  9.             sharedInstance = this.singletonCache.get(beanName);   
  10.         }   
  11.         if (sharedInstance != null) {   
  12.             if (sharedInstance == CURRENTLY_IN_CREATION) {   
  13.                 throw new BeanCurrentlyInCreationException(beanName);   
  14.             }   
  15.             if (logger.isDebugEnabled()) {   
  16.                 logger.debug("Returning cached instance of singleton bean '" + beanName + "'");   
  17.             }   
  18.             bean = getObjectForSharedInstance(name, sharedInstance);        }   
  19.   
  20.         else {   
  21.             // Check if bean definition exists in this factory.   
  22.             RootBeanDefinition mergedBeanDefinition = null;   
  23.             try {   
  24.                 mergedBeanDefinition = getMergedBeanDefinition(beanName, false);   
  25.             }   
  26.             catch (NoSuchBeanDefinitionException ex) {   
  27.                 // Not found -> check parent.   
  28.                 if (this.parentBeanFactory instanceof AbstractBeanFactory) {   
  29.                     // Delegation to parent with args only possible for AbstractBeanFactory.   
  30.                     return ((AbstractBeanFactory) this.parentBeanFactory).getBean(name, requiredType, args);   
  31.                 }   
  32.                 else if (this.parentBeanFactory != null && args == null) {   
  33.                     // No args -> delegate to standard getBean method.   
  34.                     return this.parentBeanFactory.getBean(name, requiredType);   
  35.                 }   
  36.                 throw ex;   
  37.             }   
  38.   
  39.             checkMergedBeanDefinition(mergedBeanDefinition, beanName, requiredType, args);   
  40.   
  41.             // Create bean instance.   
  42.             if (mergedBeanDefinition.isSingleton()) {   
  43.                 synchronized (this.singletonCache) {   
  44.                     // re-check singleton cache within synchronized block   
  45.                     sharedInstance = this.singletonCache.get(beanName);   
  46.                     if (sharedInstance == null) {   
  47.                         if (logger.isInfoEnabled()) {   
  48.                             logger.info("Creating shared instance of singleton bean '" + beanName + "'");   
  49.                         }   
  50.                         this.singletonCache.put(beanName, CURRENTLY_IN_CREATION);   
  51.                         try {   
  52.                             sharedInstance = createBean(beanName, mergedBeanDefinition, args);   
  53.                             this.singletonCache.put(beanName, sharedInstance);   
  54.                         }   
  55.                         catch (BeansException ex) {   
  56.                             this.singletonCache.remove(beanName);   
  57.                             throw ex;   
  58.                         }   
  59.                     }   
  60.                 }   
  61.                 bean = getObjectForSharedInstance(name, sharedInstance);   
  62.             }   
  63.             else {   
  64.                 // It's a prototype -> create a new instance.   
  65.                 bean = createBean(name, mergedBeanDefinition, args);   
  66.             }   
  67.         }   
  68.   
  69.         // Check if required type matches the type of the actual bean instance.   
  70.         if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {   
  71.             throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());   
  72.         }   
  73.         return bean;   
  74.     }   
  75. }  
public abstract class AbstractBeanFactory implements ConfigurableBeanFactory {
public Object getBean(String name, Class requiredType, Object[] args) throws BeansException {
		String beanName = transformedBeanName(name);
		Object bean = null;

		// Eagerly check singleton cache for manually registered singletons.
		Object sharedInstance = null;
		synchronized (this.singletonCache) {
			sharedInstance = this.singletonCache.get(beanName);
		}
		if (sharedInstance != null) {
			if (sharedInstance == CURRENTLY_IN_CREATION) {
				throw new BeanCurrentlyInCreationException(beanName);
			}
			if (logger.isDebugEnabled()) {
				logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
			}
			bean = getObjectForSharedInstance(name, sharedInstance);		}

		else {
			// Check if bean definition exists in this factory.
			RootBeanDefinition mergedBeanDefinition = null;
			try {
				mergedBeanDefinition = getMergedBeanDefinition(beanName, false);
			}
			catch (NoSuchBeanDefinitionException ex) {
				// Not found -> check parent.
				if (this.parentBeanFactory instanceof AbstractBeanFactory) {
					// Delegation to parent with args only possible for AbstractBeanFactory.
					return ((AbstractBeanFactory) this.parentBeanFactory).getBean(name, requiredType, args);
				}
				else if (this.parentBeanFactory != null && args == null) {
					// No args -> delegate to standard getBean method.
					return this.parentBeanFactory.getBean(name, requiredType);
				}
				throw ex;
			}

			checkMergedBeanDefinition(mergedBeanDefinition, beanName, requiredType, args);

			// Create bean instance.
			if (mergedBeanDefinition.isSingleton()) {
				synchronized (this.singletonCache) {
					// re-check singleton cache within synchronized block
					sharedInstance = this.singletonCache.get(beanName);
					if (sharedInstance == null) {
						if (logger.isInfoEnabled()) {
							logger.info("Creating shared instance of singleton bean '" + beanName + "'");
						}
						this.singletonCache.put(beanName, CURRENTLY_IN_CREATION);
						try {
							sharedInstance = createBean(beanName, mergedBeanDefinition, args);
							this.singletonCache.put(beanName, sharedInstance);
						}
						catch (BeansException ex) {
							this.singletonCache.remove(beanName);
							throw ex;
						}
					}
				}
				bean = getObjectForSharedInstance(name, sharedInstance);
			}
			else {
				// It's a prototype -> create a new instance.
				bean = createBean(name, mergedBeanDefinition, args);
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && !requiredType.isAssignableFrom(bean.getClass())) {
			throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
		}
		return bean;
	}
}





Java代碼 複製代碼
  1. public abstract class AbstractBeanFactory implements ConfigurableBeanFactory {   
  2.     protected Object getObjectForSharedInstance(String name, Object beanInstance) throws BeansException {   
  3.         String beanName = transformedBeanName(name);   
  4.   
  5.         // Don't let calling code try to dereference the   
  6.         // bean factory if the bean isn't a factory.   
  7.         if (isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {   
  8.             throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());   
  9.         }   
  10.   
  11.         // Now we have the bean instance, which may be a normal bean or a FactoryBean.   
  12.         // If it's a FactoryBean, we use it to create a bean instance, unless the   
  13.         // caller actually wants a reference to the factory.   
  14.         if (beanInstance instanceof FactoryBean) {   
  15.             if (!isFactoryDereference(name)) {   
  16.                 // Return bean instance from factory.   
  17.                 FactoryBean factory = (FactoryBean) beanInstance;   
  18.                 if (logger.isDebugEnabled()) {   
  19.                     logger.debug("Bean with name '" + beanName + "' is a factory bean");   
  20.                 }   
  21.                 try {   
  22.                     beanInstance = factory.getObject();   
  23.                 }   
  24.                 catch (Exception ex) {   
  25.                     throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);   
  26.                 }   
  27.                 if (beanInstance == null) {   
  28.                     throw new FactoryBeanNotInitializedException(   
  29.                         beanName, "FactoryBean returned null object: " +   
  30.                             "probably not fully initialized (maybe due to circular bean reference)");   
  31.                 }   
  32.             }   
  33.             else {   
  34.                 // The user wants the factory itself.   
  35.                 if (logger.isDebugEnabled()) {   
  36.                     logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");   
  37.                 }   
  38.             }   
  39.         }   
  40.   
  41.         return beanInstance;   
  42.     }   
  43. }  
public abstract class AbstractBeanFactory implements ConfigurableBeanFactory {
	protected Object getObjectForSharedInstance(String name, Object beanInstance) throws BeansException {
		String beanName = transformedBeanName(name);

		// Don't let calling code try to dereference the
		// bean factory if the bean isn't a factory.
		if (isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
			throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
		}

		// Now we have the bean instance, which may be a normal bean or a FactoryBean.
		// If it's a FactoryBean, we use it to create a bean instance, unless the
		// caller actually wants a reference to the factory.
		if (beanInstance instanceof FactoryBean) {
			if (!isFactoryDereference(name)) {
				// Return bean instance from factory.
				FactoryBean factory = (FactoryBean) beanInstance;
				if (logger.isDebugEnabled()) {
					logger.debug("Bean with name '" + beanName + "' is a factory bean");
				}
				try {
					beanInstance = factory.getObject();
				}
				catch (Exception ex) {
					throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
				}
				if (beanInstance == null) {
					throw new FactoryBeanNotInitializedException(
					    beanName, "FactoryBean returned null object: " +
							"probably not fully initialized (maybe due to circular bean reference)");
				}
			}
			else {
	 			// The user wants the factory itself.
				if (logger.isDebugEnabled()) {
					logger.debug("Calling code asked for FactoryBean instance for name '" + beanName + "'");
				}
			}
		}

		return beanInstance;
	}
}


Java代碼 複製代碼
  1. public class ProxyFactoryBean extends AdvisedSupport   
  2.     implements FactoryBean, BeanFactoryAware, AdvisedSupportListener {   
  3.     public Object getObject() throws BeansException {   
  4.         return this.singleton ? getSingletonInstance() : newPrototypeInstance();   
  5.     }   
  6.   
  7.   
  8.     private Object getSingletonInstance() {   
  9.         if (this.singletonInstance == null) {   
  10.             super.setFrozen(this.freezeProxy);   
  11.             this.singletonInstance = createAopProxy().getProxy();   
  12.         }   
  13.         return this.singletonInstance;   
  14.     }   
  15. }  
public class ProxyFactoryBean extends AdvisedSupport
    implements FactoryBean, BeanFactoryAware, AdvisedSupportListener {
	public Object getObject() throws BeansException {
		return this.singleton ? getSingletonInstance() : newPrototypeInstance();
	}


	private Object getSingletonInstance() {
		if (this.singletonInstance == null) {
			super.setFrozen(this.freezeProxy);
			this.singletonInstance = createAopProxy().getProxy();
		}
		return this.singletonInstance;
	}
}


Java代碼 複製代碼
  1. final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {   
  2.     public Object getProxy(ClassLoader classLoader) {   
  3.         if (logger.isDebugEnabled()) {   
  4.             Class targetClass = this.advised.getTargetSource().getTargetClass();   
  5.             logger.debug("Creating JDK dynamic proxy" +   
  6.                     (targetClass != null ? " for [" + targetClass.getName() + "]" : ""));   
  7.         }   
  8.         Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);   
  9.         return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);   
  10.     }   
  11. }  
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
	public Object getProxy(ClassLoader classLoader) {
		if (logger.isDebugEnabled()) {
			Class targetClass = this.advised.getTargetSource().getTargetClass();
			logger.debug("Creating JDK dynamic proxy" +
					(targetClass != null ? " for [" + targetClass.getName() + "]" : ""));
		}
		Class[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised);
		return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
	}
}


Java代碼 複製代碼
  1. public class Cglib2AopProxy implements AopProxy, Serializable {   
  2.     public Object getProxy(ClassLoader classLoader) {   
  3.         if (logger.isDebugEnabled()) {   
  4.             Class targetClass = this.advised.getTargetSource().getTargetClass();   
  5.             logger.debug("Creating CGLIB2 proxy" +   
  6.                     (targetClass != null ? " for [" + targetClass.getName() + "]" : ""));   
  7.         }   
  8.   
  9.         Enhancer enhancer = new Enhancer();   
  10.         try {   
  11.             Class rootClass = this.advised.getTargetSource().getTargetClass();   
  12.   
  13.             if (AopUtils.isCglibProxyClass(rootClass)) {   
  14.                 enhancer.setSuperclass(rootClass.getSuperclass());   
  15.             }   
  16.             else {   
  17.                 enhancer.setSuperclass(rootClass);   
  18.             }   
  19.   
  20.             enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised));   
  21.             enhancer.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class));   
  22.             enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));   
  23.   
  24.             Callback[] callbacks = getCallbacks(rootClass);   
  25.             enhancer.setCallbacks(callbacks);   
  26.   
  27.             if(CglibUtils.canSkipConstructorInterception()) {   
  28.                 enhancer.setInterceptDuringConstruction(false);   
  29.             }   
  30.                
  31.             Class[] types = new Class[callbacks.length];   
  32.             for (int x = 0; x < types.length; x++) {   
  33.                 types[x] = callbacks[x].getClass();   
  34.             }   
  35.             enhancer.setCallbackTypes(types);   
  36.   
  37.             // generate the proxy class and create a proxy instance   
  38.             Object proxy;   
  39.             if (this.constructorArgs != null) {   
  40.                 proxy = enhancer.create(this.constructorArgTypes, this.constructorArgs);   
  41.             }   
  42.             else {   
  43.                 proxy = enhancer.create();   
  44.             }   
  45.   
  46.             return proxy;   
  47.         }   
  48.         catch (CodeGenerationException ex) {   
  49.             throw new AspectException("Couldn't generate CGLIB subclass of class '" +   
  50.                     this.advised.getTargetSource().getTargetClass() + "': " +   
  51.                     "Common causes of this problem include using a final class or a non-visible class",   
  52.                     ex);   
  53.         }   
  54.         catch (IllegalArgumentException ex) {   
  55.             throw new AspectException("Couldn't generate CGLIB subclass of class '" +   
  56.                     this.advised.getTargetSource().getTargetClass() + "': " +   
  57.                     "Common causes of this problem include using a final class or a non-visible class",   
  58.                     ex);   
  59.         }   
  60.         catch (Exception ex) {   
  61.             // TargetSource.getTarget failed   
  62.             throw new AspectException("Unexpected AOP exception", ex);   
  63.         }   
  64.     }   
  65. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章