/** * Parse the elements at the root level in the document: * "import", "alias", "bean". * @param root the DOM root element of the document */ protectedvoidparseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) { if (delegate.isDefaultNamespace(root)) { // 这个分支是解析默认的 Namespace 标签 NodeListnl= root.getChildNodes(); for (inti=0; i < nl.getLength(); i++) { Nodenode= nl.item(i); if (node instanceof Element) { Elementele= (Element) node; if (delegate.isDefaultNamespace(ele)) { parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); // 这个分支就是解析用户自定义的 Namespace 标签 } }
/** * Register the {@link BeanDefinitionParser BeanDefinitionParsers} for the * '{@code config}', '{@code spring-configured}', '{@code aspectj-autoproxy}' * and '{@code scoped-proxy}' tags. */ @Override publicvoidinit() { // In 2.0 XSD as well as in 2.1 XSD. registerBeanDefinitionParser("config", newConfigBeanDefinitionParser()); registerBeanDefinitionParser("aspectj-autoproxy", newAspectJAutoProxyBeanDefinitionParser()); registerBeanDefinitionDecorator("scoped-proxy", newScopedProxyBeanDefinitionDecorator());
// Only in 2.0 XSD: moved to context namespace as of 2.1 registerBeanDefinitionParser("spring-configured", newSpringConfiguredBeanDefinitionParser()); }
细节就不在深究了,因为牵扯的代码非常多,这里我们只需要清楚第一行代码就是向 spring 容器注册了一个 AnnotationAwareAspectJAutoProxyCreator 类型的类,在 spring 容器启动过程中,会根据既定的条件完成该类的初始化及生命周期方法的调用,对了需要注意,该类对应的实例在 spring 容器中的唯一标志符就是 AUTO_PROXY_CREATOR_BEAN_NAME = "org.springframework.aop.config.internalAutoProxyCreator";。
/** * Wrap the given bean if necessary, i.e. if it is eligible for being proxied. * @param bean the raw bean instance * @param beanName the name of the bean * @param cacheKey the cache key for metadata access * @return a proxy wrapping the bean, or the raw bean instance as-is */// 判断是否需要代理,如果是,获取满足 beanClass 的 advisor,然后构建代理类:验证代理工厂长持有的目标类,然后构建 enhancer,根据 enhancer 构建代理类 class,然后通过 class 构建代理类实例,最后将 callbacks 设置到其中 protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) { return bean; } if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { return bean; // 无需代理,直接返回 } if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; // 基础类和应跳过的类直接返回 }
// 看 advisors 是否有切面增强器,有的话就在首位添加一个 DefaultPointcutAdvisor(ExposeInvocationInterceptor.ADVISOR) publicstaticbooleanmakeAdvisorChainAspectJCapableIfNecessary(List<Advisor> advisors) { // Don't add advisors to an empty list; may indicate that proxying is just not required if (!advisors.isEmpty()) { booleanfoundAspectJAdvice=false; for (Advisor advisor : advisors) { // Be careful not to get the Advice without a guard, as this might eagerly // instantiate a non-singleton AspectJ aspect... if (isAspectJAdvice(advisor)) { // 看是否是切面增强器 foundAspectJAdvice = true; break; } } // (ExposeInvocationInterceptor.ADVISOR 是放在首位的 if (foundAspectJAdvice && !advisors.contains(ExposeInvocationInterceptor.ADVISOR)) { advisors.add(0, ExposeInvocationInterceptor.ADVISOR); returntrue; } } returnfalse; }
@Override// 验证代理工厂长持有的目标类,然后构建 enhancer,根据 enhancer 构建代理类 class,然后通过 class 构建代理类实例,最后将 callbacks 设置到其中 public Object getProxy(@Nullable ClassLoader classLoader) { if (logger.isTraceEnabled()) { logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource()); }
try { // advised 就是代理工厂实例 Class<?> rootClass = this.advised.getTargetClass(); Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
// Validate the class, writing log messages as necessary. validateClassIfNecessary(proxySuperClass, classLoader); // 验证被代理类的信息,包括方法的修饰符
// Configure CGLIB Enhancer... Enhancerenhancer= createEnhancer(); // cglib 代理增强器 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); // 命名规则 enhancer.setStrategy(newClassLoaderAwareUndeclaredThrowableStrategy(classLoader)); // 获取 Callback 数组,包括 mainCallbacks 和 fixedCallbacks 两个部分 Callback[] callbacks = getCallbacks(rootClass); Class<?>[] types = newClass<?>[callbacks.length]; for (intx=0; x < types.length; x++) { types[x] = callbacks[x].getClass(); } // fixedInterceptorMap only populated at this point, after getCallbacks call above enhancer.setCallbackFilter(newProxyCallbackFilter( this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset)); enhancer.setCallbackTypes(types);
// Generate the proxy class and create a proxy instance. return createProxyClassAndInstance(enhancer, callbacks); } // 根据 enhancer 构建代理类 class,然后通过 class 构建代理类实例,最后将 callbacks 设置到其中 catch (CodeGenerationException | IllegalArgumentException ex) { thrownewAopConfigException("Could not generate CGLIB subclass of " + 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 thrownewAopConfigException("Unexpected AOP exception", ex); } }
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)throws Throwable { ObjectoldProxy=null; booleansetProxyContext=false; Objecttarget=null; TargetSourcetargetSource=this.advised.getTargetSource(); try { if (this.advised.exposeProxy) { // Make invocation available if necessary. oldProxy = AopContext.setCurrentProxy(proxy); // 如果要暴露代理类,那么就将代理类保存到 AopContext setProxyContext = true; } // Get as late as possible to minimize the time we "own" the target, in case it comes from a pool... target = targetSource.getTarget(); Class<?> targetClass = (target != null ? target.getClass() : null); List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); Object retVal; // 尝试从缓存中获取 interceptorList,没有的话就从当前实例中获取(获取 Advised 的全部 advisors,看 advisor 是否适配当前方法,适配的话从 advisor 中获取到 Advice,然后将其添加到 interceptorList 集合返回) // 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. Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args); retVal = methodProxy.invoke(target, argsToUse); // 这里是没有拦截器的方法调用方式 } else { // We need to create a method invocation... // 将代理相关的参数构建为 CglibMethodInvocation,进行处理,也就是说通过 CglibMethodInvocation 来触发 advice 的调用 retVal = newCglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed(); } retVal = processReturnType(proxy, target, method, retVal); return retVal; } finally { if (target != null && !targetSource.isStatic()) { targetSource.releaseTarget(target); } if (setProxyContext) { // Restore old proxy. AopContext.setCurrentProxy(oldProxy); } } }
public Object proceed()throws Throwable { // We start with an index of -1 and increment early. if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) { return invokeJoinpoint(); // 这里就是触发连接点方法 }
ObjectinterceptorOrInterceptionAdvice=// 逐个获取 interceptorOrInterceptionAdvice this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex); 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. // 对逐个获取的 interceptorOrInterceptionAdvice 进行 invoke 调用 return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this); // 参数为通过代理各项参数构建的 CglibMethodInvocation } }
@Override public Object invoke(MethodInvocation mi)throws Throwable { if (!(mi instanceof ProxyMethodInvocation)) { thrownewIllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi); } ProxyMethodInvocationpmi= (ProxyMethodInvocation) mi; ProceedingJoinPointpjp= lazyGetProceedingJoinPoint(pmi); JoinPointMatchjpm= getJoinPointMatch(pmi); return invokeAdviceMethod(pjp, jpm, null, null); }
// As above, but in this case we are given the join point. protected Object invokeAdviceMethod(JoinPoint jp, @Nullable JoinPointMatch jpMatch, @Nullable Object returnValue, @Nullable Throwable t)throws Throwable {