Spring源码解析——AOP

在Bean的初始化化后会执行Bean的后置处理器方法applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName)

public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
			throws BeansException {

		Object result = existingBean;
		for (BeanPostProcessor processor : getBeanPostProcessors()) {
			Object current = processor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}

实际进行处理的是 postProcessAfterInitialization 方法,在 bean 实例化之后的处理,在这一步中进行里代理增强,所以来看下这个方法:

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			// earlyProxyReferences中存的是哪些提前进行了AOP的bean,beanName:AOP之前的对象
			// 注意earlyProxyReferences中并没有存AOP之后的代理对象  BeanPostProcessor
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				// 没有提前进行过AOP,则进行AOP
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		// 为什么不返回代理对象呢?
		return bean;   //
	}

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
		// 当前这个bean不用被代理
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
			return bean;
		}

		// 如果是基础bean,或者@Aspect修饰的类不需要被代理
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

		// Create proxy if we have advice.
		// 获取当前beanClass所匹配的advisors
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);

		// 如果匹配的advisors不等于null,那么则进行代理,并返回代理对象
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			// 基于bean对象和Advisor创建代理对象
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			// 存一个代理对象的类型
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

来提取一下核心流程:

  1. 获取增强方法或者增强器 @Before 、@After 之类的,就是增强方法,AOP 处理时,要先找出这些增强方法。
  2. 根据获取的增强进行代理 找到增强方法后,需要对这些增强方法进行增强代理,实际上这个 bean 已经不完全是原来的类型了,会变成代理后的类型。

获取增强方法或者增强器

protected Object[] getAdvicesAndAdvisorsForBean(
			Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {

		// 针对当前bean查找合格的Advisor
		List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
		if (advisors.isEmpty()) {
			return DO_NOT_PROXY;
		}
		return advisors.toArray();
	}

// 查找合格的Advisor(和beanClass匹配)
	protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
		// 得到所有的Advisor
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
		// 得到和beanClass匹配的Advisor
		List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);

		extendAdvisors(eligibleAdvisors);
		if (!eligibleAdvisors.isEmpty()) {
			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
		}

		// 返回匹配的Advisor
		return eligibleAdvisors;
	}

protected List<Advisor> findCandidateAdvisors() {
		// Add all the Spring advisors found according to superclass rules.
		// Advisor=Pointcut+Advice (切点加建议) ,获得到所有Advisor类型的bean
		List<Advisor> advisors = super.findCandidateAdvisors();

		// Build Advisors for all AspectJ aspects in the bean factory.
		// 找的是通过AspectJ的方式定义的Advisor
		if (this.aspectJAdvisorsBuilder != null) {
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}

public List<Advisor> buildAspectJAdvisors() {
		List<String> aspectNames = this.aspectBeanNames;

		if (aspectNames == null) {
			synchronized (this) {
				aspectNames = this.aspectBeanNames;
				if (aspectNames == null) {
					List<Advisor> advisors = new ArrayList<>();
					aspectNames = new ArrayList<>();
					// 拿到beanFactory中所有的bean
					String[] beanNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
							this.beanFactory, Object.class, true, false);
					for (String beanName : beanNames) {
						// 是不是一个合格的Aspect的beanName
						if (!isEligibleBean(beanName)) {
							continue;
						}
						// We must be careful not to instantiate beans eagerly as in this case they
						// would be cached by the Spring container but would not have been weaved.
						Class<?> beanType = this.beanFactory.getType(beanName);
						if (beanType == null) {
							continue;
						}
						// beanType是不是一个切面,判断beanType上是否存在@Aspect注解
						if (this.advisorFactory.isAspect(beanType)) {
							aspectNames.add(beanName);
							AspectMetadata amd = new AspectMetadata(beanType, beanName);
							if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
								MetadataAwareAspectInstanceFactory factory =
										new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
								// 解析得到Advisor
								List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory);
								if (this.beanFactory.isSingleton(beanName)) {
									this.advisorsCache.put(beanName, classAdvisors);
								}
								else {
									this.aspectFactoryCache.put(beanName, factory);
								}
								advisors.addAll(classAdvisors);
							}
							else {
								// Per target or per this.
								if (this.beanFactory.isSingleton(beanName)) {
									throw new IllegalArgumentException("Bean with name '" + beanName +
											"' is a singleton, but aspect instantiation model is not singleton");
								}
								MetadataAwareAspectInstanceFactory factory =
										new PrototypeAspectInstanceFactory(this.beanFactory, beanName);
								this.aspectFactoryCache.put(beanName, factory);
								advisors.addAll(this.advisorFactory.getAdvisors(factory));
							}
						}
					}
					this.aspectBeanNames = aspectNames;
					return advisors;
				}
			}
		}

		if (aspectNames.isEmpty()) {
			return Collections.emptyList();
		}
		List<Advisor> advisors = new ArrayList<>();
		for (String aspectName : aspectNames) {
			List<Advisor> cachedAdvisors = this.advisorsCache.get(aspectName);
			if (cachedAdvisors != null) {
				advisors.addAll(cachedAdvisors);
			}
			else {
				MetadataAwareAspectInstanceFactory factory = this.aspectFactoryCache.get(aspectName);
				advisors.addAll(this.advisorFactory.getAdvisors(factory));
			}
		}
		return advisors;
	}

根据获取的增强进行代理

代理对象实例最终是使用AopProxy.getProxy()得到的,他的调用是在AopProxyFactory.createAopProxy(AdvisedSupport config,createAopProxy)有两个结果。一个是基于接口的JDK动态代理JdkDynamicAopProxy,一个是基于CGLib的生成类代理ObjenesisCglibAopProxy。源码如下:

protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {

		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}

		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.copyFrom(this);	// 从this复制配置参数
		// 是否指定了必须用cglib进行代理
		if (!proxyFactory.isProxyTargetClass()) {
			// 如果没有指定,那么则判断是不是应该进行cglib代理(判断BeanDefinition中是否指定了要用cglib)
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				// 是否进行jdk动态代理
				evaluateProxyInterfaces(beanClass, proxyFactory); // 判断beanClass有没有实现接口
			}
		}

		// 添加一些commonInterceptors
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		proxyFactory.addAdvisors(advisors);	// 向ProxyFactory中添加advisor
		proxyFactory.setTargetSource(targetSource); // 被代理的对象
		customizeProxyFactory(proxyFactory);

		proxyFactory.setFrozen(this.freezeProxy);	//
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}

		// 生成代理对象
		return proxyFactory.getProxy(getProxyClassLoader());
	}

public Object getProxy(@Nullable ClassLoader classLoader) {
		// 根据不同的情况得到不同的动态代理工厂,cglib或jdk动态代理
		return createAopProxy().getProxy(classLoader);
	}

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() || Proxy.isProxyClass(targetClass)) {
				// 如果目标类是接口,或者已经是Jdk的动态代理类,则创建jdk动态代理
				return new JdkDynamicAopProxy(config);
			}
			// 否则创建Cglib动态代理
			return new ObjenesisCglibAopProxy(config);
		}
		else {
			// 如果声明创建Jdk动态代理则返回Jdk动态代理
			return new JdkDynamicAopProxy(config);
		}
	}

JDK动态代理

JdkDynamicAopProxy中getProxy会返回:

@Override
	public Object getProxy(@Nullable ClassLoader classLoader) {
		if (logger.isTraceEnabled()) {
			logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
		}
		// 获取所有需要代理的接口
		Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
		findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
		// 返回代理对象的实例
		return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
	}

自己作为InvocationHandler注册,看他的invoke方法

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	MethodInvocation invocation;
	Object oldProxy = null;
	boolean setProxyContext = false;

	TargetSource targetSource = this.advised.targetSource;
	Class<?> targetClass = null;
	Object target = null;

	try {
		if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
			// The target does not implement the equals(Object) method itself.
			// 没有声明equals方法,调用equals方法时,委托调用。
			return equals(args[0]);
		}
		else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
			// The target does not implement the hashCode() method itself.
			// 没有声明hashCode方法,调用hashCode方法时,委托调用。
			return hashCode();
		}
		else if (method.getDeclaringClass() == DecoratingProxy.class) {
			// There is only getDecoratedClass() declared -> dispatch to proxy config.
			// 如果调用的方法是DecoratingProxy中的方法,因为其中只有一个getDecoratedClass方法,这里直接返回被装饰的Class即可
			return AopProxyUtils.ultimateTargetClass(this.advised);
		}
		else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
				method.getDeclaringClass().isAssignableFrom(Advised.class)) {
			// 代理不是不透明的,且是接口中声明的方法,且是Advised或其父接口的方法,则直接调用构造时传入的advised对象的相应方法
			// Service invocations on ProxyConfig with the proxy config...
			return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
		}

		Object retVal;

		if (this.advised.exposeProxy) {
			// Make invocation available if necessary.
		    // 如果暴露代理,则用AopContext保存当前代理对象。用于多级代理时获取当前的代理对象,一个有效应用是同类中调用方法,代理拦截器会无效。可以使用AopContext.currentProxy()获得代理对象并调用。
			oldProxy = AopContext.setCurrentProxy(proxy);
			setProxyContext = true;
		}

		// May be null. Get as late as possible to minimize the time we "own" the target,
		// in case it comes from a pool.
		target = targetSource.getTarget();
		if (target != null) {
			targetClass = target.getClass();
		}

		// Get the interception chain for this
		// 这里是关键,获得拦截链chain,是通过advised对象,即config对象获得的。
		method.
		List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

		// Check whether we have any advice. If we don't, we can fallback on direct
		// reflective invocation of the target, and avoid creating a MethodInvocation.
		if (chain.isEmpty()) {
		    // 如果链是空,则直接调用被代理对象的方法
			// We can skip creating a MethodInvocation: just invoke the target directly
			// Note that the final invoker must be an InvokerInterceptor so we know it does
			// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
			Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
			retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
		}
		else {
			// We need to create a method invocation...
			// 否则创建一个MethodInvocation对象,用于链式调用拦截器链chain中的拦截器。
			invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
			// Proceed to the joinpoint through the interceptor chain.
			// 开始执行链式调用,得到返回结果
			retVal = invocation.proceed();
		}

		// Massage return value if necessary.
		Class<?> returnType = method.getReturnType();
		if (retVal != null && retVal == target &&
				returnType != Object.class && returnType.isInstance(proxy) &&
				!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
			// 处理返回值
			// 如果返回结果是this,即原始对象,且方法所在类没有标记为RawTargetAccess(不是RawTargetAccess的实现类或者子接口),则返回代理对象。
			// Special case: it returned "this" and the return type of the method
			// is type-compatible. Note that we can't help if the target sets
			// a reference to itself in another returned object.
			retVal = proxy;
		}
		else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
			throw new AopInvocationException(
					"Null return value from advice does not match primitive return type for: " + method);
		}
		return retVal;
	}
	finally {
		if (target != null && !targetSource.isStatic()) {
			// Must have come from TargetSource.
			targetSource.releaseTarget(target);
		}
		if (setProxyContext) {
			// Restore old proxy.
			AopContext.setCurrentProxy(oldProxy);
		}
	}
}

创建 JDK 代理过程中,主要的工作时创建了一个拦截器链,并使用 ReflectiveMethodInvocation 类进行封装,封装之后,逐一调用它的 proceed 方法, 用来实现在目标方法的前置增强和后置增强。

public Object proceed() throws Throwable {
	// 执行完所有增强器后执行切点方法
	if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
		return invokeJoinpoint();
	}
	// 获取下一个要执行的拦截器
	Object interceptorOrInterceptionAdvice =
			this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
	if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
		// 动态匹配
		InterceptorAndDynamicMethodMatcher dm =
				(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
		Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
		if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
			return dm.interceptor.invoke(this);
		}
		else {
			// 匹配失败,跳过拦截器,直接返回
			return proceed();
		}
	}
	else {
		return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
	}
}
JdkDynamicAopProxy创建代理对象过程
  1. 获取生成代理对象所需要实现的接口集合
    a. 获取通过ProxyFactory.addInterface()所添加的接口,如果没有通过ProxyFactory.addInterface()添加接口,那么则看ProxyFactory.setTargetClass()所设置的targetClass是不是一个接口,把接口添加到结果集合中
    b. 同时把SpringProxy、Advised、DecoratingProxy这几个接口也添加到结果集合中去
  2. 确定好要代理的集合之后,就利用Proxy.newProxyInstance()生成一个代理对象
JdkDynamicAopProxy创建的代理对象执行过程
  1. 如果通过ProxyFactory.setExposeProxy()把exposeProxy设置为了true,那么则把代理对象设置到一个ThreadLocal(currentProxy)中去。
  2. 获取通过ProxyFactory所设置的target,如果设置的是targetClass,那么target将为null
  3. 根据当前所调用的方法对象寻找ProxyFactory中所添加的并匹配的Advisor,并且把Advisor封装为MethodInterceptor返回,得到MethodInterceptor链叫做chain
  4. 如果chain为空,则直接执行target对应的当前方法,如果target为null会报错
  5. 如果chain不为空,则会依次执行chain中的MethodInterceptor
    a. 如果当前MethodInterceptor是MethodBeforeAdviceInterceptor,那么则先执行Advisor中所advice的before()方法,然后执行下一个MethodInterceptor
    b. 如果当前MethodInterceptor是AfterReturningAdviceInterceptor,那么则先执行下一个MethodInterceptor,拿到返回值之后,再执行Advisor中所advice的afterReturning()方法

Cglib动态代理

ObjenesisCglibAopProxy继承自CglibAopProxy,整体对外暴露的接口和方法是与上面一致的,只有其真实实现换成了Cglib而已。

public Object getProxy(ClassLoader classLoader) {
	if (logger.isDebugEnabled()) {
		logger.debug("Creating CGLIB proxy: target source is " + this.advised.getTargetSource());
	}

	try {
		Class<?> rootClass = this.advised.getTargetClass();
		Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");

		Class<?> proxySuperClass = rootClass;
		if (ClassUtils.isCglibProxyClass(rootClass)) {
			proxySuperClass = rootClass.getSuperclass();
			Class<?>[] additionalInterfaces = rootClass.getInterfaces();
			for (Class<?> additionalInterface : additionalInterfaces) {
				this.advised.addInterface(additionalInterface);
			}
		}

		// Validate the class, writing log messages as necessary.
		validateClassIfNecessary(proxySuperClass, classLoader);

		// Configure CGLIB Enhancer...
		// 使用cglib库的enhancer,配置之后生成代理对象实例
		Enhancer enhancer = createEnhancer();
		if (classLoader != null) {
			enhancer.setClassLoader(classLoader);
			if (classLoader instanceof SmartClassLoader &&
					((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
				enhancer.setUseCache(false);
			}
		}
		enhancer.setSuperclass(proxySuperClass);
		enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
		// 命名策略是类名中加$$
		enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
		// 设置类生成策略,直接生成类的字节码byte[],可以深入研究
		enhancer.setStrategy(new ClassLoaderAwareUndeclaredThrowableStrategy(classLoader));
        
        // 获取所有的callback,此时callback是cglib 的,getCallbacks中会把advisors封装成callback传入
		Callback[] callbacks = getCallbacks(rootClass);
		Class<?>[] types = new Class<?>[callbacks.length];
		// 生成callback类型数组
		for (int x = 0; x < types.length; x++) {
			types[x] = callbacks[x].getClass();
		}
		// fixedInterceptorMap only populated at this point, after getCallbacks call above
		// 加入是否需要进行callback的过滤器,根据filter的返回的int值,cglib会执行不同的callback,索引分别对应上面的callback数组的索引:
		// 0:AOP_PROXY、1:INVOKE_TARGET、2:NO_OVERRIDE、3:DISPATCH_TARGET、4:DISPATCH_ADVISED、5:INVOKE_EQUALS、6:INVOKE_HASHCODE
		enhancer.setCallbackFilter(new ProxyCallbackFilter(
				this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
		enhancer.setCallbackTypes(types);

		// Generate the proxy class and create a proxy instance.
		return createProxyClassAndInstance(enhancer, callbacks);
	}
	catch (CodeGenerationException ex) {
		throw new AopConfigException("Could not generate CGLIB subclass of class [" +
				this.advised.getTargetClass() + "]: " +
				"Common causes of this problem include using a final class or a non-visible class",
				ex);
	}
	catch (IllegalArgumentException ex) {
		throw new AopConfigException("Could not generate CGLIB subclass of class [" +
				this.advised.getTargetClass() + "]: " +
				"Common causes of this problem include using a final class or a non-visible class",
				ex);
	}
	catch (Throwable ex) {
		// TargetSource.getTarget() failed
		throw new AopConfigException("Unexpected AOP exception", ex);
	}
}

protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
    // 不拦截构造方法
	enhancer.setInterceptDuringConstruction(false);
	// 设置拦截器callback
	enhancer.setCallbacks(callbacks);
	// 创建代理对象实例
	return (this.constructorArgs != null ?
			enhancer.create(this.constructorArgTypes, this.constructorArgs) :
			enhancer.create());
}

直接看方法拦截器部分。注册拦截器是在getProxy方法中,注册进去的是cglib中的callback:

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

private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
	// Parameters used for optimization 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).
	// 生成aopInterceptor,用于AOP调用,这是调用拦截器链的核心,详看后面。
	Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

	// 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;
	// 下面根据不同情况,返回不同的Callback。
	// targetSource的isStatic为true表示targetSource中的target是静态的不改变的,故直接缓存target即可。
	// 为false则代表是动态的target,每次都需要getTarget来获取,这两种返回不同的callback,以便后续执行时使用不同情况的target。
	// 而exposeProxy代表是否暴露代理对象到AopProxyContext中。
	// 为true代表暴露,false不暴露。都需要返回不同的callback。
	// 故总共有四种callback,且四种callback都有一个processReturnType的过程,同JdkDynamicAopProxy中的处理返回值。前面的操作也与JdkDynamicAopProxy中开始的目的相同。
	if (exposeProxy) {
		targetInterceptor = isStatic ?
				new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
				new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource());
	}
	else {
		targetInterceptor = isStatic ?
				new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
				new DynamicUnadvisedInterceptor(this.advised.getTargetSource());
	}

	// Choose a "direct to target" dispatcher (used for
	// unadvised calls to static targets that cannot return this).
	// 直接调用target的callback
	Callback targetDispatcher = isStatic ?
			new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp();
    // callbackFilter返回的是callback的索引,用于调用这里的索引值对应的callback。
	Callback[] mainCallbacks = new Callback[] {
			aopInterceptor,  // for normal advice
			// 经过callbackFilter后,不需要被advice的对象,直接调用这个interceptor,性能最高。
			targetInterceptor,  // invoke target without considering advice, if optimized
			new SerializableNoOp(),  // no override for methods mapped to this
			targetDispatcher,
			// 调用advised中方法时,直接分配到advised中。
			this.advisedDispatcher,
			// equals方法
			new EqualsInterceptor(this.advised),
			// hashCode方法
			new HashCodeInterceptor(this.advised)
	};

	Callback[] callbacks;

	// If the target is a static one and the advice chain is frozen,
	// then we can make some optimizations by sending the AOP calls
	// direct to the target using the fixed chain for that method.
	// 这是一个优化,如果target是个不可变的静态对象,且advice链是固定不变的,则进行优化。内容见后面。
	if (isStatic && isFrozen) {
		Method[] methods = rootClass.getMethods();
		Callback[] fixedCallbacks = new Callback[methods.length];
		this.fixedInterceptorMap = new HashMap<String, Integer>(methods.length);

		// TODO: small memory optimization here (can skip creation for methods with no advice)
		for (int x = 0; x < methods.length; x++) {
		    // 遍历所有方法,返回每个方法的拦截器链,并为每个方法生成一个包含拦截器链的callback。
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(methods[x], rootClass);
			fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
					chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
			// 注意,这个fixedInterceptorMap还与callbackFilter关联,以便达到filter的目的。
			// 同时保存索引到map中,以用于callbackFilter中返回索引。
			this.fixedInterceptorMap.put(methods[x].toString(), x);
		}

		// Now copy both the callbacks from mainCallbacks
		// and fixedCallbacks into the callbacks array.
		// 聚合所有callback
		callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
		System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
		System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
		// 标记fixedInterceptor的偏移量,也会传入filter。
		this.fixedInterceptorOffset = mainCallbacks.length;
	}
	else {
		callbacks = mainCallbacks;
	}
	return callbacks;
}

上面提到callbackFilter的作用是返回需要调用的callback的序号,与上面的getCallbacks有比较大的关联,源码如下

// aopInterceptor: DynamicAdvisedInterceptor
private static final int AOP_PROXY = 0;
// targetInterceptor: 没有advise的方法
private static final int INVOKE_TARGET = 1;
// noOp: SerializableNoOp
private static final int NO_OVERRIDE = 2;
// targetDispatcher: isStatic ? StaticDispatcher : SerializableNoOp
private static final int DISPATCH_TARGET = 3;
// advisedDispatcher: AdvisedDispatcher
private static final int DISPATCH_ADVISED = 4;
// EqualsInterceptor
private static final int INVOKE_EQUALS = 5;
// HashCodeInterceptor
private static final int INVOKE_HASHCODE = 6;
// 其他索引直接通过fixedInterceptorMap获得
// 下面逻辑基本对应JdkDynamicAopProxy中判断逻辑
public int accept(Method method) {
	if (AopUtils.isFinalizeMethod(method)) {
	    // 如果是final的方法,则返回NO_OVERRIDE
		logger.debug("Found finalize() method - using NO_OVERRIDE");
		return NO_OVERRIDE;
	}
	if (!this.advised.isOpaque() && method.getDeclaringClass().isInterface() &&
			method.getDeclaringClass().isAssignableFrom(Advised.class)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Method is declared on Advised interface: " + method);
		}
		// advised上的方法,直接调用advised对象的对应方法
		return DISPATCH_ADVISED;
	}
	// We must always proxy equals, to direct calls to this.
	if (AopUtils.isEqualsMethod(method)) {
	    // 返回调用equals
		logger.debug("Found 'equals' method: " + method);
		return INVOKE_EQUALS;
	}
	// We must always calculate hashCode based on the proxy.
	if (AopUtils.isHashCodeMethod(method)) {
	    // 返回调用hashCode
		logger.debug("Found 'hashCode' method: " + method);
		return INVOKE_HASHCODE;
	}
	Class<?> targetClass = this.advised.getTargetClass();
	// Proxy is not yet available, but that shouldn't matter.
	List<?> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
	// 判断是否有拦截器链
	boolean haveAdvice = !chain.isEmpty();
	boolean exposeProxy = this.advised.isExposeProxy();
	boolean isStatic = this.advised.getTargetSource().isStatic();
	boolean isFrozen = this.advised.isFrozen();
	if (haveAdvice || !isFrozen) {
	    // 如果有advice或者不是冻结的(不可改变的)
		// If exposing the proxy, then AOP_PROXY must be used.
		if (exposeProxy) {
			if (logger.isDebugEnabled()) {
				logger.debug("Must expose proxy on advised method: " + method);
			}
			// 如果需要暴露Proxy则返回aop代理
			return AOP_PROXY;
		}
		String key = method.toString();
		// Check to see if we have fixed interceptor to serve this method.
		// Else use the AOP_PROXY.
		if (isStatic && isFrozen && this.fixedInterceptorMap.containsKey(key)) {
		    // 通过fixedInterceptorMap获得对应索引,返回callback。
			if (logger.isDebugEnabled()) {
				logger.debug("Method has advice and optimizations are enabled: " + method);
			}
			// We know that we are optimizing so we can use the FixedStaticChainInterceptors.
			int index = this.fixedInterceptorMap.get(key);
			return (index + this.fixedInterceptorOffset);
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to apply any optimizations to advised method: " + method);
			}
			return AOP_PROXY;
		}
	}
	else {
		// See if the return type of the method is outside the class hierarchy of the target type.
		// If so we know it never needs to have return type massage and can use a dispatcher.
		// If the proxy is being exposed, then must use the interceptor the correct one is already
		// configured. If the target is not static, then we cannot use a dispatcher because the
		// target needs to be explicitly released after the invocation.
		if (exposeProxy || !isStatic) {
		    // 如果需要暴露,则要使用targetInterceptor
			return INVOKE_TARGET;
		}
		Class<?> returnType = method.getReturnType();
		if (returnType.isAssignableFrom(targetClass)) {
		    // 如果返回类型是被代理类型的父类或者接口,有可能是返回this引用,需要用INVOKE_TARGET对返回值做处理
			if (logger.isDebugEnabled()) {
				logger.debug("Method return type is assignable from target type and " +
						"may therefore return 'this' - using INVOKE_TARGET: " + method);
			}
			return INVOKE_TARGET;
		}
		else {
			if (logger.isDebugEnabled()) {
				logger.debug("Method return type ensures 'this' cannot be returned - " +
						"using DISPATCH_TARGET: " + method);
			}
			// 不需要拦截,直接返回目标调用
			return DISPATCH_TARGET;
		}
	}
}

这里的核心是把advised对象转成了Callback,注册到Enhancer中,那么拦截器链的执行应该是在

Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);

// 下面这段代码在我们调试Spring的时候回经常进来,特别是进入一个Bean的方法后再返回上一级调用时,最常见的就是这里。
// 这段代码基本与JdkDynamicAopProxy的invoke方法一致
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
	Object oldProxy = null;
	boolean setProxyContext = false;
	Class<?> targetClass = null;
	Object target = null;
	try {
		if (this.advised.exposeProxy) {
		    // 需要则暴露
			// Make invocation available if necessary.
			oldProxy = AopContext.setCurrentProxy(proxy);
			setProxyContext = true;
		}
		// May be null. Get as late as possible to minimize the time we
		// "own" the target, in case it comes from a pool...
		target = getTarget();
		if (target != null) {
			targetClass = target.getClass();
		}
		// 获取拦截器链
		List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
		Object retVal;
		// Check whether we only have one InvokerInterceptor: that is,
		// no real advice, but just reflective invocation of the target.
		if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
			// We can skip creating a MethodInvocation: just invoke the target directly.
			// Note that the final invoker must be an InvokerInterceptor, so we know
			// it does nothing but a reflective operation on the target, and no hot
			// swapping or fancy proxying.
			// 如果链是空且是public方法,则直接调用
			Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
			retVal = methodProxy.invoke(target, argsToUse);
		}
		else {
			// We need to create a method invocation...
			// 否则创建一个CglibMethodInvocation以便驱动拦截器链
			retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
		}
		// 处理返回值,同JDK动态代理
		retVal = processReturnType(proxy, target, method, retVal);
		return retVal;
	}
	finally {
		if (target != null) {
			releaseTarget(target);
		}
		if (setProxyContext) {
			// Restore old proxy.
			AopContext.setCurrentProxy(oldProxy);
		}
	}
}

这个和上面的jdk动态代理的invoke就比较像了,一样有List chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

最终的执行则是:

retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();

一样是转换为了aopalliance的invocation。注意CglibMethodInvocation是ReflectiveMethodInvocation的子类。区别在于CglibMethodInvocation内维护了cglib的MethodProxy,调用链执行完进行最终真实调用时,是调用了methodProxy.invoke(this.target, this.arguments)。

ObjenesisCglibAopProxy创建代理对象过程
  1. 创建Enhancer
  2. 设置Enhancer的superClass为通过ProxyFactory.setTarget()所设置的对象的类
  3. 设置Enhancer的interfaces为通过ProxyFactory.addInterface()所添加的接口,以及SpringProxy、Advised接口
  4. 设置Enhancer的Callbacks为DynamicAdvisedInterceptor
  5. 最后通过Enhancer创建一个代理对象
ObjenesisCglibAopProxy创建的代理对象执行过程

执行过程主要就看DynamicAdvisedInterceptor中的实现,执行逻辑和JdkDynamicAopProxy中是一样的。

总结

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值