//注册BeanDefinition @Override publicvoidregisterBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { booleancandidateFound=false; Set<String> annTypes = importingClassMetadata.getAnnotationTypes(); for (String annType : annTypes) { AnnotationAttributescandidate= AnnotationConfigUtils.attributesFor(importingClassMetadata, annType); if (candidate == null) { continue; } Objectmode= candidate.get("mode"); ObjectproxyTargetClass= candidate.get("proxyTargetClass"); if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() && Boolean.class == proxyTargetClass.getClass()) { candidateFound = true; if (mode == AdviceMode.PROXY) { //代理模式 //注册事务AOP的入口类InfrastructureAdvisorAutoProxyCreator,实际上这个AOP入口类起不了作用 AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry); if ((Boolean) proxyTargetClass) { //如果是CGLOB子类代理模式 AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); return; } } } } if (!candidateFound && logger.isInfoEnabled()) { Stringname= getClass().getSimpleName(); logger.info(String.format("%s was imported but no annotations were found " + "having both 'mode' and 'proxyTargetClass' attributes of type " + "AdviceMode and boolean respectively. This means that auto proxy " + "creator registration and configuration may not have occurred as " + "intended, and components may not be proxied as expected. Check to " + "ensure that %s has been @Import'ed on the same class where these " + "annotations are declared; otherwise remove the import of %s " + "altogether.", name, name, name)); } }
/** * Stores the auto proxy creator classes in escalation order. * <p> * 优先级上升list */ privatestaticfinal List<Class<?>> APC_PRIORITY_LIST = newArrayList<>(3);
static { // Set up the escalation list... APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class); APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class); APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class); }
if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) { //如果已经存在直接返回 if (this.advisedBeans.containsKey(cacheKey)) { returnnull; } //是否基础构件(基础构建不需要代理):Advice、Pointcut、Advisor、AopInfrastructureBean这四类都算基础构建 if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { //添加进advisedBeans ConcurrentHashMap<k=Object,v=Boolean>标记是否需要增强实现,这里基础构建bean不需要代理,都置为false,供后面postProcessAfterInitialization实例化后使用。 this.advisedBeans.put(cacheKey, Boolean.FALSE); returnnull; } }
// TargetSource是spring aop预留给我们用户自定义实例化的接口,如果存在TargetSource就不会默认实例化,而是按照用户自定义的方式实例化,咱们没有定义,不进入 // Create proxy here if we have a custom TargetSource. // Suppresses unnecessary default instantiation of the target bean: // The TargetSource will handle target instances in a custom fashion. TargetSourcetargetSource= getCustomTargetSource(beanClass, beanName); if (targetSource != null) { if (StringUtils.hasLength(beanName)) { this.targetSourcedBeans.add(beanName); } Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource); Objectproxy= createProxy(beanClass, beanName, specificInterceptors, targetSource); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; }
/** * 创建Bean的代理的入口 * Create a proxy with the configured interceptors if the bean is * identified as one to proxy by the subclass. * * @see #getAdvicesAndAdvisorsForBean */ @Override public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) { if (bean != null) { //从缓存中获取代理实例 ObjectcacheKey= getCacheKey(bean.getClass(), beanName); // 1.判断当前bean是否需要被代理,如果需要则进行封装 if (this.earlyProxyReferences.remove(cacheKey) != bean) { //如果需要包装成代理实例 return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; }
/** * AOP 调用的入口 * @param invocation * @return * @throws Throwable */ @Override @Nullable public Object invoke(MethodInvocation invocation)throws Throwable { // Work out the target class: may be {@code null}. // The TransactionAttributeSource should be passed the target class // as well as the method, which may be from an interface. Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) { // Standard transaction demarcation with getTransaction and commit/rollback calls. //创建事务 TransactionInfotxInfo= createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
Object retVal; try { // This is an around advice: Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. //火炬传递 // 这里就是一个环绕增强,在这个proceed前后可以自己定义增强实现 retVal = invocation.proceedWithInvocation(); } catch (Throwable ex) { // target invocation exception // 根据事务定义的,该异常需要回滚就回滚,否则提交事务 completeTransactionAfterThrowing(txInfo, ex); throw ex; } finally { //清空当前事务信息,重置为老的 cleanupTransactionInfo(txInfo); }
if (vavrPresent && VavrDelegate.isVavrTry(retVal)) { // Set rollback-only in case of Vavr failure matching our rollback rules... TransactionStatusstatus= txInfo.getTransactionStatus(); if (status != null && txAttr != null) { retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status); } } //返回结果之前提交事务 commitTransactionAfterReturning(txInfo); return retVal;
// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in. try { Objectresult= ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> { TransactionInfotxInfo= prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status); try { ObjectretVal= invocation.proceedWithInvocation(); if (vavrPresent && VavrDelegate.isVavrTry(retVal)) { // Set rollback-only in case of Vavr failure matching our rollback rules... retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status); } return retVal; } catch (Throwable ex) { // 如果该异常需要回滚 if (txAttr.rollbackOn(ex)) { // A RuntimeException: will lead to a rollback. if (ex instanceof RuntimeException) { // 如果是运行时异常返回 throw (RuntimeException) ex; } else { // 如果是其它异常都抛ThrowableHolderException thrownewThrowableHolderException(ex); } } else { // 如果不需要回滚 // A normal return value: will lead to a commit. // 定义异常,最终就直接提交事务了 throwableHolder.throwable = ex; returnnull; } } finally { //清空当前事务信息,重置为老的 cleanupTransactionInfo(txInfo); } });
// Check result state: It might indicate a Throwable to rethrow. if (throwableHolder.throwable != null) { // 上抛异常 throw throwableHolder.throwable; } return result; } catch (ThrowableHolderException ex) { throw ex.getCause(); } catch (TransactionSystemException ex2) { if (throwableHolder.throwable != null) { logger.error("Application exception overridden by commit exception", throwableHolder.throwable); ex2.initApplicationException(throwableHolder.throwable); } throw ex2; } catch (Throwable ex2) { if (throwableHolder.throwable != null) { logger.error("Application exception overridden by commit exception", throwableHolder.throwable); } throw ex2; } } }
@Override @Nullable public Object proceed()throws Throwable { // We start with an index of -1 and increment early. // 1.如果所有拦截器都执行完毕(index是从-1开始,所以跟size - 1比较),则直接使用反射调用连接点(也就是我们原本的方法) //如果执行链中的advice全部执行完,则直接调用joinPoint方法,就是被代理方法 if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { return invokeJoinpoint(); }
// 2.每次调用时,将索引的值递增,并通过索引拿到要执行的拦截器 ObjectinterceptorOrInterceptionAdvice= this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); // 3.判断拦截器是否为InterceptorAndDynamicMethodMatcher类型(动态方法匹配拦截器) if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) { // Evaluate dynamic method matcher here: static part will already have // been evaluated and found to match. // 进行动态匹配。在此评估动态方法匹配器:静态部件已经过评估并且发现匹配。 InterceptorAndDynamicMethodMatcherdm= (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 { // Dynamic matching failed. // Skip this interceptor and invoke the next in the chain. // 动态匹配失败。跳过此拦截器并调用链中的下一个。 return proceed(); } } else { // It's an interceptor, so we just invoke it: The pointcut will have // been evaluated statically before this object was constructed. // 4.只是一个普通的拦截器,则触发拦截器链责任链的调用,并且参数为ReflectiveMethodInvocation本身 //调用MethodInterceptor中的invoke方法 return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); } }