Spring源码阅读 - AOP

AOP

① 代理类创建:

② invoke:

PS : AOP是在DI之后,对exposedObject执行applyBeanPostProcessorsAfterInitialization()过程中发生的。AbstractAutoProxyCreator.postProcessAfterInitialization()

AbstractAutowireCapableBeanFactory:

  1. 完成依赖注入之后,获得一个exposedObject,对exposedObject执行初始化操作
AbstractAutowireCapableBeanFactory#doCreateBean():
    	// Bean对象的初始化,依赖注入在此触发
		Object exposedObject = bean;
		try {
			// DI 7: 依赖注入bean - 将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象
			populateBean(beanName, mbd, instanceWrapper);

			// AOP 1: 完成依赖注入后,获得可用的原生对象,对原生对象进行初始化操作
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}

AbstractAutowireCapableBeanFactory#initializeBean():
		//BeanPostProcessor后置处理器的postProcessAfterInitialization回调方法的调用,为Bean实例初始化之后加入一些处理
		if (mbd == null || !mbd.isSynthetic()) {
			// IOC 2:AOP需要在对象初始化方法执行之后进行代理
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}

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

		Object result = existingBean;
		// 遍历容器为所创建的Bean添加的所有BeanPostProcessor后置处理器
		for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
			//调用Bean实例所有的后置处理中的初始化后处理方法,为Bean实例对象在初始化之后做一些自定义的处理操作
			// IOC 3 : AbstractAutoProxyCreator.postProcessAfterInitialization()
			Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
			if (current == null) {
				return result;
			}
			result = current;
		}
		return result;
	}
  1. AOP代理:AbstractAutoProxyCreator#postProcessAfterInitialization()
// AbstractAutoProxyCreator#postProcessAfterInitialization()
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
		if (bean != null) {
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			// earlyProxyReferences与代理类之间的循环依赖有关,如果代理类出现循环依赖,则会调用getEarlyBeanReference()方法提前触发代理。
			if (!this.earlyProxyReferences.contains(cacheKey)) {
				// AOP 4 : 代理核心逻辑
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}

// AOP 4 : 代理核心逻辑
AbstractAutoProxyCreator#wrapIfNecessary():
		// AOP 5:扫描所有的相关的方法(PointCut原始方法,哪些方法需要被代理),构建方法与通知的关联
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE);
			// AOP 7: 创建代理对象
			Object proxy = createProxy(
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}

// AOP 5:
AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean()
    // AOP 6 : 查找所有与该类有关的通知
	List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);

// AOP 6 : 查找所有与该类有关的通知
AbstractAdvisorAutoProxyCreator#findEligibleAdvisors():
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
		// 获取所有通知
		List<Advisor> candidateAdvisors = findCandidateAdvisors();

		// 获取与该类有关的通知
		List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);

		extendAdvisors(eligibleAdvisors);
		if (!eligibleAdvisors.isEmpty()) {
			// AOP : 排序(如果通知存在权重值,则根据权重值排序)
			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
		}
		return eligibleAdvisors;
	}
  1. AOP创建InvocationHandler及代理对象
// AOP 7: 创建代理对象
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 继承于 AdvisedSupport,作为ObjenesisCglibAopProxy/JdkDynamicAopProxy(AdvisedSupport config)参数。
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.copyFrom(this);

		if (!proxyFactory.isProxyTargetClass()) {
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}

		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		proxyFactory.addAdvisors(advisors);
		proxyFactory.setTargetSource(targetSource);
		customizeProxyFactory(proxyFactory);

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

		// AOP 8 :(DefaultAopProxyFactory) - 根据具体情况,获取JDK Proxy或CGLib的InvocationHandler类,并由InvocationHandler创建代理对象。
		return proxyFactory.getProxy(getProxyClassLoader());
	}

JdkDynamicAopProxy.invoke()

  1. 代理执行入口:invoke()
	// AOP :代码织入,链式调用advisor,反射调用主业务方法
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	...		
			// AOP :获得目标对象的类
			target = targetSource.getTarget();
			Class<?> targetClass = (target != null ? target.getClass() : null);

			// AOP 9:将通知构建成责任链 --- 以方法作为key,获取与该方法关联的advices(所有符合条件的advices),封装成InterceptorAndDynamicMethodMatcher.
			// InterceptorAndDynamicMethodMatcher.invoke(): MethodInvocation.proceed()方法 + 通知织入代码。
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

			// AOP :如果没有可以应用到此方法的通知(Interceptor),此直接反射调用 method.invoke(target, args)
			if (chain.isEmpty()) {
				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
			}
			else {
				// AOP 10 :由MethodInvocation对象负责调配责任链的调用以及最后主业务方法的反射调用
				invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
				retVal = invocation.proceed();
			}
	...		
	}
  1. 构建通知拦截器列表
// AOP : 构建拦截器链列表
AdvisedSupport#getInterceptorsAndDynamicInterceptionAdvice():
	// 从缓存中取,若没有则遍历构建
	if (cached == null) {
		// AOP 10 : 获取符合条件的拦截器 List<MethodInterceptor>
		cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
			this, method, targetClass);
		// 存入缓存
		this.methodCache.put(cacheKey, cached);
	}

DefaultAdvisorChainFactory#getInterceptorsAndDynamicInterceptionAdvice():
	// AOP :这里实际上注册一系列AdvisorAdapter,用于将Advisor转化成MethodInterceptor
	AdvisorAdapterRegistry registry = GlobalAdvisorAdapterRegistry.getInstance();
	// AOP : 将Advisor转化成Interceptor -- DefaultAdvisorAdapterRegistry.getInterceptors()
	MethodInterceptor[] interceptors = registry.getInterceptors(advisor);
  1. Adapter创建拦截器对象
//DefaultAdvisorAdapterRegistry#getInterceptors():
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
		List<MethodInterceptor> interceptors = new ArrayList<>(3);
		Advice advice = advisor.getAdvice();
		if (advice instanceof MethodInterceptor) {
			interceptors.add((MethodInterceptor) advice);
		}
		for (AdvisorAdapter adapter : this.adapters) {
			if (adapter.supportsAdvice(advice)) {
				// AOP : 依次让不同的adapter处理advisor生成对应MethodInterceptor。
				// 例如:AfterReturningAdviceInterceptor() -> AfterReturningAdviceInterceptor
				interceptors.add(adapter.getInterceptor(advisor));
			}
		}
		if (interceptors.isEmpty()) {
			throw new UnknownAdviceTypeException(advisor.getAdvice());
		}
		return interceptors.toArray(new MethodInterceptor[interceptors.size()]);
	}
  1. 拦截器具体实现
public class MethodBeforeAdviceInterceptor implements MethodInterceptor, Serializable {
	private MethodBeforeAdvice advice;
	/**
	 * Create a new MethodBeforeAdviceInterceptor for the given advice.
	 * @param advice the MethodBeforeAdvice to wrap
	 */
	public MethodBeforeAdviceInterceptor(MethodBeforeAdvice advice) {
		Assert.notNull(advice, "Advice must not be null");
		this.advice = advice;
	}

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
        // 织入代码
		this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
		// 链式执行
        return mi.proceed();
	}
}
  1. ReflectiveMethodInvocation控制拦截器链的调用以及主业务方法的调用
// ReflectiveMethodInvocation.proceed():
public Object proceed() throws Throwable {
	// 当拦截器链已经递归完成,最后执行原生对象的方法
	if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
		return invokeJoinpoint();
	}

    // 由currentInterceptorIndex计数器控制当前执行的拦截器对象
	Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
	
    // 运行过程中需动态匹配joinPoint的拦截器
	if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
		InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
		// 动态匹配:运行时参数是否满足匹配条件
		if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
			return dm.interceptor.invoke(this);
		}
		else {
			// 匹配失败时,略过当前Intercetpor,调用下一次Interceptor
			return proceed();
		}
	}
	else {
		// 之前已经完成匹配的拦截器,只需执行逻辑即可
		return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
	}
}
posted @ 2021-01-29 19:52  祁奇  阅读(78)  评论(0编辑  收藏  举报