⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cglib2aopproxy.java

📁 一个关于Spring框架的示例应用程序,简单使用,可以参考.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 * Copyright 2002-2004 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.framework;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.cglib.core.CodeGenerationException;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.CallbackFilter;
import net.sf.cglib.proxy.Dispatcher;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import net.sf.cglib.proxy.NoOp;
import net.sf.cglib.transform.impl.UndeclaredThrowableStrategy;
import org.aopalliance.aop.AspectException;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.support.AopUtils;

/**
 * CGLIB2-based AopProxy implementation for the Spring AOP framework.
 * Requires CGLIB2 on the class path.
 * <p/>
 * <p>Objects of this type should be obtained through proxy factories,
 * configured by an AdvisedSupport object. This class is internal to the
 * Spring AOP framework and need not be used directly by client code.
 * <p/>
 * <p>DefaultAopProxyFactory will automatically create CGLIB2-based proxies
 * if necessary, for example in case of proxying a target class. See
 * DefaultAopProxyFactory's javadoc for details.
 * <p/>
 * <p>Proxies created using this class are thread-safe if the underlying
 * (target) class is thread-safe.
 * <p/>
 * <p>Built and tested against CGLIB 2.0.2, as of Spring 1.1.
 * Basic functionality will still work on CGLIB 2.0.1, but it is
 * generally recommended to use CGLIB 2.0.2 or later.
 *
 * @author Rod Johnson
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @see DefaultAopProxyFactory
 * @see AdvisedSupport#setProxyTargetClass
 */
public class Cglib2AopProxy implements AopProxy, Serializable {

	// Constants for CGLIB callback array indices
	private static final int AOP_PROXY = 0;

	private static final int INVOKE_TARGET = 1;

	private static final int NO_OVERRIDE = 2;

	private static final int DISPATCH_TARGET = 3;

	private static final int DISPATCH_ADVISED = 4;

	private static final int INVOKE_EQUALS = 5;


	/**
	 * Static to optimize serialization
	 */
	protected final static Log logger = LogFactory.getLog(Cglib2AopProxy.class);

	/**
	 * Config used to configure this proxy
	 */
	protected final AdvisedSupport advised;

	private Object[] constructorArgs;

	private Class[] constructorArgTypes;

	/**
	 * Dispatcher used for methods on <code>Advised</code>
	 */
	private final transient AdvisedDispatcher advisedDispatcher = new AdvisedDispatcher();

	private transient int fixedInterceptorOffset;

	private transient Map fixedInterceptorMap;


	/**
	 * Create a new Cglib2AopProxy for the given config.
	 *
	 * @throws AopConfigException if the config is invalid. We try to throw an informative
	 *                            exception in this case, rather than let a mysterious failure happen later.
	 */
	protected Cglib2AopProxy(AdvisedSupport config) throws AopConfigException {
		if (config == null) {
			throw new AopConfigException("Cannot create AopProxy with null ProxyConfig");
		}
		if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
			throw new AopConfigException("Cannot create AopProxy with no advisors and no target source");
		}
		//DK - is this check really necessary?
		//should this 'config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE' be enough?
		if (config.getTargetSource().getTargetClass() == null) {
			throw new AopConfigException("Either an interface or a target is required for proxy creation");
		}
		this.advised = config;
	}

	/**
	 * Set constructor arguments to use for creating the proxy.
	 *
	 * @param constructorArgs     the constructor argument values
	 * @param constructorArgTypes the constructor argument types
	 */
	protected void setConstructorArguments(Object[] constructorArgs, Class[] constructorArgTypes) {
		if (constructorArgs == null || constructorArgTypes == null) {
			throw new IllegalArgumentException("Both constructorArgs and constructorArgTypes need to be specified");
		}
		if (constructorArgs.length != constructorArgTypes.length) {
			throw new IllegalArgumentException("Number of constructorArgs (" + constructorArgs.length +
					") must match number of constructorArgTypes (" + constructorArgTypes.length + ")");
		}
		this.constructorArgs = constructorArgs;
		this.constructorArgTypes = constructorArgTypes;
	}


	public Object getProxy() {
		return getProxy(null);
	}

	public Object getProxy(ClassLoader classLoader) {
		if (logger.isDebugEnabled()) {
			Class targetClass = this.advised.getTargetSource().getTargetClass();
			logger.debug("Creating CGLIB2 proxy" +
					(targetClass != null ? " for [" + targetClass.getName() + "]" : ""));
		}

		Enhancer enhancer = new Enhancer();
		try {
			Class rootClass = this.advised.getTargetSource().getTargetClass();

			if (AopUtils.isCglibProxyClass(rootClass)) {
				enhancer.setSuperclass(rootClass.getSuperclass());
			}
			else {
				enhancer.setSuperclass(rootClass);
			}

			enhancer.setCallbackFilter(new ProxyCallbackFilter(this.advised));
			enhancer.setStrategy(new UndeclaredThrowableStrategy(UndeclaredThrowableException.class));
			enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));

			Callback[] callbacks = getCallbacks(rootClass);
			enhancer.setCallbacks(callbacks);

			if(CglibUtils.canSkipConstructorInterception()) {
				enhancer.setInterceptDuringConstruction(false);
			}
			
			Class[] types = new Class[callbacks.length];
			for (int x = 0; x < types.length; x++) {
				types[x] = callbacks[x].getClass();
			}
			enhancer.setCallbackTypes(types);

			// generate the proxy class and create a proxy instance
			Object proxy;
			if (this.constructorArgs != null) {
				proxy = enhancer.create(this.constructorArgTypes, this.constructorArgs);
			}
			else {
				proxy = enhancer.create();
			}

			return proxy;
		}
		catch (CodeGenerationException ex) {
			throw new AspectException("Couldn't generate CGLIB subclass of class '" +
					this.advised.getTargetSource().getTargetClass() + "': " +
					"Common causes of this problem include using a final class or a non-visible class",
					ex);
		}
		catch (IllegalArgumentException ex) {
			throw new AspectException("Couldn't generate CGLIB subclass of class '" +
					this.advised.getTargetSource().getTargetClass() + "': " +
					"Common causes of this problem include using a final class or a non-visible class",
					ex);
		}
		catch (Exception ex) {
			// TargetSource.getTarget failed
			throw new AspectException("Unexpected AOP exception", ex);
		}
	}

	private Callback[] getCallbacks(Class rootClass) throws Exception {
		// parameters used for optimisation choices
		boolean exposeProxy = this.advised.isExposeProxy();
		boolean isFrozen = this.advised.isFrozen();
		boolean isStatic = this.advised.getTargetSource().isStatic();

		// Choose an "aop" interceptor (used for AOP calls).
		Callback aopInterceptor = new DynamicAdvisedInterceptor();

		// Choose a "straight to target" interceptor. (used for calls that are
		// unadvised but can return this). May be required to expose the proxy.
		Callback targetInterceptor = null;

		if (exposeProxy) {
			targetInterceptor = isStatic ?
					(Callback) new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
					(Callback) new DynamicUnadvisedExposedInterceptor();
		}
		else {
			targetInterceptor = isStatic ?
					(Callback) new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
					(Callback) new DynamicUnadvisedInterceptor();
		}

		// Choose a "direct to target" dispatcher (used for
		// unadvised calls to static targets that cannot return this).
		Callback targetDispatcher = isStatic ?
				(Callback) new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();

		Callback[] mainCallbacks = new Callback[]{
			aopInterceptor, // for normal advice
			targetInterceptor, // invoke target without considering advice, if optimized
			new SerializableNoOp(), // no override for methods mapped to this
			targetDispatcher, this.advisedDispatcher,
			new EqualsInterceptor(this.advised)
		};

		Callback[] callbacks;

		// If the target is a static one and the advice chain is frozen,
		// then we can make some optimisations by sending the AOP calls
		// direct to the target using the fixed chain for that method.
		if (isStatic && isFrozen) {
			Callback[] fixedCallbacks = null;

			Method[] methods = rootClass.getMethods();
			fixedCallbacks = new Callback[methods.length];

			this.fixedInterceptorMap = new HashMap();

			// TODO: small memory optimisation here (can skip creation for
			// methods with no advice)
			for (int x = 0; x < methods.length; x++) {
				List chain = this.advised.getAdvisorChainFactory().getInterceptorsAndDynamicInterceptionAdvice(this.advised, null, methods[x], rootClass);
				fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetSource().getTargetClass());
				this.fixedInterceptorMap.put(methods[x].toString(), new Integer(x));
			}

			// now copy both the callbacks from mainCallbacks
			// and fixedCallbacks into the callbacks array.
			callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];

			for (int x = 0; x < mainCallbacks.length; x++) {
				callbacks[x] = mainCallbacks[x];
			}

			for (int x = 0; x < fixedCallbacks.length; x++) {
				callbacks[x + mainCallbacks.length] = fixedCallbacks[x];
			}

			this.fixedInterceptorOffset = mainCallbacks.length;
		}
		else {
			callbacks = mainCallbacks;
		}
		return callbacks;
	}

	/**
	 * Wrap a return of this if necessary to be the proxy
	 */
	private static Object massageReturnTypeIfNecessary(Object proxy, Object target, Object retVal) {
		// Massage return value if necessary
		if (retVal != null && retVal == target) {
			// Special case: it returned "this"
			// Note that we can't help if the target sets a reference
			// to itself in another returned object.
			retVal = proxy;
		}
		return retVal;
	}


	public int hashCode() {
		return 0;
	}

	/**
	 * Checks to see if this CallbackFilter is the same CallbackFilter used for
	 * another proxy.
	 */
	public boolean equals(Object other) {
		if (other == null) {
			return false;
		}
		if (other == this) {
			return true;
		}

		Cglib2AopProxy otherCglibProxy = null;
		if (other instanceof Cglib2AopProxy) {
			otherCglibProxy = (Cglib2AopProxy) other;
		}
		else {
			// not a valid comparison
			return false;
		}

		return AopProxyUtils.equalsInProxy(advised, otherCglibProxy.advised);
	}


	/**
	 * Serializable replacement for CGLIB's NoOp interface.
	 * Public to allow use elsewhere in the framework.
	 */
	public static class SerializableNoOp implements NoOp, Serializable {

	}

	/**
	 * Method interceptor used for static targets with no advice chain. The call
	 * is passed directly back to the target. Used when the proxy needs to be
	 * exposed and it can't be determined that the method won't return
	 * <code>this</code>.
	 */
	private static class StaticUnadvisedInterceptor implements MethodInterceptor, Serializable {

		private final Object target;

		public StaticUnadvisedInterceptor(Object target) {
			this.target = target;
		}

		public Object intercept(Object proxy, Method method, Object[] args,
				MethodProxy methodProxy) throws Throwable {

			Object retVal = methodProxy.invoke(target, args);
			return massageReturnTypeIfNecessary(proxy, target, retVal);
		}
	}


	/**
	 * Method interceptor used for static targets with no advice chain, when the
	 * proxy is to be exposed.
	 */
	private static class StaticUnadvisedExposedInterceptor implements MethodInterceptor, Serializable {

		private final Object target;

		public StaticUnadvisedExposedInterceptor(Object target) {
			this.target = target;
		}

		public Object intercept(Object proxy, Method method, Object[] args,
				MethodProxy methodProxy) throws Throwable {
			Object oldProxy = null;
			try {
				oldProxy = AopContext.setCurrentProxy(proxy);
				Object retVal = methodProxy.invoke(target, args);
				return massageReturnTypeIfNecessary(proxy, target, retVal);
			}
			finally {
				AopContext.setCurrentProxy(oldProxy);
			}
		}
	}


	/**
	 * Interceptor used to invoke a dynamic target without creating a method
	 * invocation or evaluating an advice chain. (We know there was no advice
	 * for this method.)
	 */
	private class DynamicUnadvisedInterceptor implements MethodInterceptor, Serializable {

		public Object intercept(Object proxy, Method method, Object[] args,
				MethodProxy methodProxy) throws Throwable {

			Object target = advised.getTargetSource().getTarget();

			try {
				Object retVal = methodProxy.invoke(target, args);

				return massageReturnTypeIfNecessary(proxy, target, retVal);
			}
			finally {
				advised.getTargetSource().releaseTarget(target);
			}
		}
	}


	/**
	 * Interceptor for unadvised dynamic targets when the proxy needs exposing.
	 */
	private class DynamicUnadvisedExposedInterceptor implements MethodInterceptor, Serializable {

		public Object intercept(Object proxy, Method method, Object[] args,
				MethodProxy methodProxy) throws Throwable {

			Object oldProxy = null;
			Object target = advised.getTargetSource().getTarget();

			try {
				oldProxy = AopContext.setCurrentProxy(proxy);

				Object retVal = methodProxy.invoke(target, args);

				return massageReturnTypeIfNecessary(proxy, target, retVal);
			}
			finally {
				AopContext.setCurrentProxy(oldProxy);
				advised.getTargetSource().releaseTarget(target);
			}
		}
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -