// 注册 aop 相关类@NullablepublicstaticBeanDefinitionregisterAutoProxyCreatorIfNecessary(BeanDefinitionRegistryregistry,@NullableObjectsource){returnregisterOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class,registry,source);}privatestaticBeanDefinitionregisterOrEscalateApcAsRequired(Class<?>cls,BeanDefinitionRegistryregistry,@NullableObjectsource){Assert.notNull(registry,"BeanDefinitionRegistry must not be null");// 检查之前是否注册过if(registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)){BeanDefinitionapcDefinition=registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);// 和当前注册类不一样if(!cls.getName().equals(apcDefinition.getBeanClassName())){intcurrentPriority=findPriorityForClass(apcDefinition.getBeanClassName());intrequiredPriority=findPriorityForClass(cls);// 比较优先级if(currentPriority<requiredPriority){// 重新设置 beanClassNameapcDefinition.setBeanClassName(cls.getName());}}returnnull;}// 之前没有注册过RootBeanDefinitionbeanDefinition=newRootBeanDefinition(cls);beanDefinition.setSource(source);// order 是最大值beanDefinition.getPropertyValues().add("order",Ordered.HIGHEST_PRECEDENCE);// 基础类beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);// 注册 beanDefinitionregistry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME,beanDefinition);returnbeanDefinition;}
// 从上到下,优先级依次变高static{// Set up the escalation list...APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);}
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented// 导入配置类@Import(AspectJAutoProxyRegistrar.class)public@interfaceEnableAspectJAutoProxy{/**
* Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
* to standard Java interface-based proxies. The default is {@code false}.
*/// 如果为 true,则为 cglib proxybooleanproxyTargetClass()defaultfalse;/**
* Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
* for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
* Off by default, i.e. no guarantees that {@code AopContext} access will work.
* @since 4.3.1
*/booleanexposeProxy()defaultfalse;}
classAspectJAutoProxyRegistrarimplementsImportBeanDefinitionRegistrar{/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableAspectJAutoProxy#proxyTargetClass()} attribute on the importing
* {@code @Configuration} class.
*/@OverridepublicvoidregisterBeanDefinitions(AnnotationMetadataimportingClassMetadata,BeanDefinitionRegistryregistry){// 激活 aop 相关类 AnnotationAwareAspectJAutoProxyCreatorAopConfigUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry);AnnotationAttributesenableAspectJAutoProxy=AnnotationConfigUtils.attributesFor(importingClassMetadata,EnableAspectJAutoProxy.class);if(enableAspectJAutoProxy!=null){if(enableAspectJAutoProxy.getBoolean("proxyTargetClass")){// 强制使用 proxyTargetClass = true, 使用 cglib 来实现代理AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);}if(enableAspectJAutoProxy.getBoolean("exposeProxy")){// 强制使用 exposeProxy = true, 可以用 AopContext#currentProxy 获取代理对象AopConfigUtils.forceAutoProxyCreatorToExposeProxy(registry);}}}}
// bean 实例化之前会执行这个方法@OverridepublicObjectpostProcessBeforeInstantiation(Class<?>beanClass,StringbeanName){ObjectcacheKey=getCacheKey(beanClass,beanName);if(!StringUtils.hasLength(beanName)||!this.targetSourcedBeans.contains(beanName)){if(this.advisedBeans.containsKey(cacheKey)){returnnull;}// 基础类 或者 需要跳过if(isInfrastructureClass(beanClass)||shouldSkip(beanClass,beanName)){this.advisedBeans.put(cacheKey,Boolean.FALSE);returnnull;}}// 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.// 获取自定义的 targetSource, 默认为空,所以不会在这个方法中生成代理对象TargetSourcetargetSource=getCustomTargetSource(beanClass,beanName);if(targetSource!=null){if(StringUtils.hasLength(beanName)){this.targetSourcedBeans.add(beanName);}// 获取这个类的 advisorObject[]specificInterceptors=getAdvicesAndAdvisorsForBean(beanClass,beanName,targetSource);// 创建代理对象Objectproxy=createProxy(beanClass,beanName,specificInterceptors,targetSource);this.proxyTypes.put(cacheKey,proxy.getClass());returnproxy;}// 返回 null,会继续实例化returnnull;}
// 创建代理对象protectedObjectcreateProxy(Class<?>beanClass,@NullableStringbeanName,@NullableObject[]specificInterceptors,TargetSourcetargetSource){...// 代理工厂ProxyFactoryproxyFactory=newProxyFactory();proxyFactory.copyFrom(this);// 添加代理接口if(proxyFactory.isProxyTargetClass()){// Explicit handling of JDK proxy targets and lambdas (for introduction advice scenarios)if(Proxy.isProxyClass(beanClass)||ClassUtils.isLambdaClass(beanClass)){// Must allow for introductions; can't just set interfaces to the proxy's interfaces only.for(Class<?>ifc:beanClass.getInterfaces()){proxyFactory.addInterface(ifc);}}}else{// No proxyTargetClass flag enforced, let's apply our default checks...if(shouldProxyTargetClass(beanClass,beanName)){proxyFactory.setProxyTargetClass(true);}else{evaluateProxyInterfaces(beanClass,proxyFactory);}}// 获取 advisorAdvisor[]advisors=buildAdvisors(beanName,specificInterceptors);proxyFactory.addAdvisors(advisors);proxyFactory.setTargetSource(targetSource);...// 获取代理对象returnproxyFactory.getProxy(classLoader);}