在 refresh() 中,首先对上下文进行预处理,设置一些必要的参数,然后获取 IOC 容器,并对 IOC 容器进行一些参数进行设置,然后调用工厂处理器注册相关的 bean 进入上下文
publicabstractclassAbstractApplicationContextextendsDefaultResourceLoaderimplementsConfigurableApplicationContext{privatefinalObject startupShutdownMonitor =newObject();...@Overridepublicvoidrefresh()throwsBeansException,IllegalStateException{synchronized(this.startupShutdownMonitor){// 1. 上下文设置一些必要的参数prepareRefresh();// 2. 获取 IOC 容器ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();// 3. 对 IOC 容器进行一些参数设置prepareBeanFactory(beanFactory);try{// Allows post-processing of the bean factory in context subclasses.postProcessBeanFactory(beanFactory);// 4. 调用工厂处理器,注册 bean 到 IOC 容器invokeBeanFactoryPostProcessors(beanFactory);...}catch(BeansException ex){...}...}}protectedvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory){// 5. 对 IOC 容器调用 beanFactoryPostProcessors 来处理 PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory,getBeanFactoryPostProcessors());// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)if(beanFactory.getTempClassLoader()==null&& beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)){beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory));beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));}}}
finalclassPostProcessorRegistrationDelegate{...publicstaticvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory,List<BeanFactoryPostProcessor> beanFactoryPostProcessors){// Invoke BeanDefinitionRegistryPostProcessors first, if any.Set<String> processedBeans =newHashSet<>();if(beanFactory instanceofBeanDefinitionRegistry){BeanDefinitionRegistry registry =(BeanDefinitionRegistry) beanFactory;List<BeanFactoryPostProcessor> regularPostProcessors =newArrayList<>();List<BeanDefinitionRegistryPostProcessor> registryProcessors =newArrayList<>();for(BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors){if(postProcessor instanceofBeanDefinitionRegistryPostProcessor){BeanDefinitionRegistryPostProcessor registryProcessor =(BeanDefinitionRegistryPostProcessor) postProcessor;registryProcessor.postProcessBeanDefinitionRegistry(registry);registryProcessors.add(registryProcessor);}else{regularPostProcessors.add(postProcessor);}}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!// Separate between BeanDefinitionRegistryPostProcessors that implement// PriorityOrdered, Ordered, and the rest.List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors =newArrayList<>();// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.String[] postProcessorNames =beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class,true,false);for(String ppName : postProcessorNames){if(beanFactory.isTypeMatch(ppName,PriorityOrdered.class)){currentRegistryProcessors.add(beanFactory.getBean(ppName,BeanDefinitionRegistryPostProcessor.class));processedBeans.add(ppName);}}sortPostProcessors(currentRegistryProcessors, beanFactory);registryProcessors.addAll(currentRegistryProcessors);// 1. 调用 bean 注册处理器,处理类的注册 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);...}...}privatestaticvoidinvokeBeanDefinitionRegistryPostProcessors(Collection<?extendsBeanDefinitionRegistryPostProcessor> postProcessors,BeanDefinitionRegistry registry){for(BeanDefinitionRegistryPostProcessor postProcessor : postProcessors){// 2. 其中 postProcessors 只有一个类,即为 ConfigurationClassPostProcessor postProcessor.postProcessBeanDefinitionRegistry(registry);}}}
这时候就会交由 ConfigurationClassPostProcessor 来注册 bean 到 IOC 容器中
publicclassConfigurationClassPostProcessorimplementsBeanDefinitionRegistryPostProcessor,PriorityOrdered,ResourceLoaderAware,BeanClassLoaderAware,EnvironmentAware{privatefinalSet<Integer> registriesPostProcessed =newHashSet<>();...@OverridepublicvoidpostProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry){int registryId =System.identityHashCode(registry);if(this.registriesPostProcessed.contains(registryId)){thrownewIllegalStateException("postProcessBeanDefinitionRegistry already called on this post-processor against "+ registry);}if(this.factoriesPostProcessed.contains(registryId)){thrownewIllegalStateException("postProcessBeanFactory already called on this post-processor against "+ registry);}this.registriesPostProcessed.add(registryId);// 1. 注册 bean 到 IOC 容器中processConfigBeanDefinitions(registry);}}
classConfigurationClassParser{...protectedvoidprocessConfigurationClass(ConfigurationClass configClass,Predicate<String> filter)throwsIOException{if(this.conditionEvaluator.shouldSkip(configClass.getMetadata(),ConfigurationPhase.PARSE_CONFIGURATION)){return;}ConfigurationClass existingClass =this.configurationClasses.get(configClass);if(existingClass !=null){if(configClass.isImported()){if(existingClass.isImported()){existingClass.mergeImportedBy(configClass);}// Otherwise ignore new imported config class; existing non-imported class overrides it.return;}else{// Explicit bean definition found, probably replacing an import.// Let's remove the old one and go with the new one.this.configurationClasses.remove(configClass);this.knownSuperclasses.values().removeIf(configClass::equals);}}// Recursively process the configuration class and its superclass hierarchy.SourceClass sourceClass =asSourceClass(configClass, filter);do{// 1. 真正处理 @Configuration 的方法,其中 sourceClass 为 com.lagou.SpringBootMytestApplicationsourceClass =doProcessConfigurationClass(configClass, sourceClass, filter);}while(sourceClass !=null);this.configurationClasses.put(configClass, configClass);}}
publicabstractclassBeanDefinitionReaderUtils{...publicstaticvoidregisterBeanDefinition(BeanDefinitionHolder definitionHolder,BeanDefinitionRegistry registry)throwsBeanDefinitionStoreException{// Register bean definition under primary name.String beanName = definitionHolder.getBeanName();// 1. 通过 BeanDefinitionRegistry 注册扫描出来的类,这里是先注册 com.lagou.config.MyDataSourceConfig,后注册 com.lagou.controller.TestControllerregistry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());// Register aliases for bean name, if any.String[] aliases = definitionHolder.getAliases();if(aliases !=null){for(String alias : aliases){registry.registerAlias(beanName, alias);}}}}
(续)
最后会把这些扫描出来的类,放到 beanDefinitionMap 属性中
publicclassDefaultListableBeanFactoryextendsAbstractAutowireCapableBeanFactoryimplementsConfigurableListableBeanFactory,BeanDefinitionRegistry,Serializable{/** List of bean definition names, in registration order. */privatevolatileList<String> beanDefinitionNames =newArrayList<>(256);/** Map of bean definition objects, keyed by bean name. */privatefinalMap<String,BeanDefinition> beanDefinitionMap =newConcurrentHashMap<>(256);...@OverridepublicvoidregisterBeanDefinition(String beanName,BeanDefinition beanDefinition)throwsBeanDefinitionStoreException{Assert.hasText(beanName,"Bean name must not be empty");Assert.notNull(beanDefinition,"BeanDefinition must not be null");if(beanDefinition instanceofAbstractBeanDefinition){try{((AbstractBeanDefinition) beanDefinition).validate();}catch(BeanDefinitionValidationException ex){thrownewBeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,"Validation of bean definition failed", ex);}}BeanDefinition existingDefinition =this.beanDefinitionMap.get(beanName);if(existingDefinition !=null){if(!isAllowBeanDefinitionOverriding()){thrownewBeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);}elseif(existingDefinition.getRole()< beanDefinition.getRole()){// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTUREif(logger.isInfoEnabled()){logger.info("Overriding user-defined bean definition for bean '"+ beanName +"' with a framework-generated bean definition: replacing ["+existingDefinition +"] with ["+ beanDefinition +"]");}}elseif(!beanDefinition.equals(existingDefinition)){if(logger.isDebugEnabled()){logger.debug("Overriding bean definition for bean '"+ beanName +"' with a different definition: replacing ["+ existingDefinition +"] with ["+ beanDefinition +"]");}}else{if(logger.isTraceEnabled()){logger.trace("Overriding bean definition for bean '"+ beanName +"' with an equivalent definition: replacing ["+ existingDefinition +"] with ["+ beanDefinition +"]");}}this.beanDefinitionMap.put(beanName, beanDefinition);}else{if(hasBeanCreationStarted()){// Cannot modify startup-time collection elements anymore (for stable iteration)synchronized(this.beanDefinitionMap){// 1. 把对应的 beanDefinition 注册到 beanDefinitionMap 中this.beanDefinitionMap.put(beanName, beanDefinition);List<String> updatedDefinitions =newArrayList<>(this.beanDefinitionNames.size()+1);updatedDefinitions.addAll(this.beanDefinitionNames);updatedDefinitions.add(beanName);this.beanDefinitionNames = updatedDefinitions;removeManualSingletonName(beanName);}}else{// Still in startup registration phasethis.beanDefinitionMap.put(beanName, beanDefinition);this.beanDefinitionNames.add(beanName);removeManualSingletonName(beanName);}this.frozenBeanDefinitionNames =null;}if(existingDefinition !=null||containsSingleton(beanName)){resetBeanDefinition(beanName);}elseif(isConfigurationFrozen()){clearByTypeCache();}}}
classConfigurationClassParser{privatefinalComponentScanAnnotationParser componentScanParser;privatefinalConditionEvaluator conditionEvaluator;privatefinalEnvironment environment;...@NullableprotectedfinalSourceClassdoProcessConfigurationClass(ConfigurationClass configClass,SourceClass sourceClass,Predicate<String> filter)throwsIOException{if(configClass.getMetadata().isAnnotated(Component.class.getName())){// Recursively process any member (nested) classes firstprocessMemberClasses(configClass, sourceClass, filter);}// Process any @PropertySource annotationsfor(AnnotationAttributes propertySource :AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),PropertySources.class,org.springframework.context.annotation.PropertySource.class)){if(this.environment instanceofConfigurableEnvironment){processPropertySource(propertySource);}else{logger.info("Ignoring @PropertySource annotation on ["+ sourceClass.getMetadata().getClassName()+"]. Reason: Environment must implement ConfigurableEnvironment");}}// 扫描处理所有 @ComponentScan 注解Set<AnnotationAttributes> componentScans =AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),ComponentScans.class,ComponentScan.class);if(!componentScans.isEmpty()&&!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(),ConfigurationPhase.REGISTER_BEAN)){for(AnnotationAttributes componentScan : componentScans){// 解析 @ComponentScan 的注解,然后把相关对象Set<BeanDefinitionHolder> scannedBeanDefinitions =this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());// Check the set of scanned definitions for any further config classes and parse recursively if neededfor(BeanDefinitionHolder holder : scannedBeanDefinitions){BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();if(bdCand ==null){bdCand = holder.getBeanDefinition();}// 1. 判断扫描的类是不是用 @Configuration 标记if(ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand,this.metadataReaderFactory)){// 2. 是的话继续解析该配置类 parse(bdCand.getBeanClassName(), holder.getBeanName());}}}}...}protectedfinalvoidparse(@NullableString className,String beanName)throwsIOException{Assert.notNull(className,"No bean class name for configuration class bean definition");MetadataReader reader =this.metadataReaderFactory.getMetadataReader(className);// 3. 形成递归调用解析processConfigurationClass(newConfigurationClass(reader, beanName),DEFAULT_EXCLUSION_FILTER);}}
直到这里我们就能够明白如何把主类所在的类路径下相关的类通过 @ComponentScan 注册到 IOC 容器中,像相关的 @Import、@ImportResource 注册,也是在 processConfigurationClass() 这个方法里解析,下节再解析
AHR(Account Health Rating)即亚马逊账户健康评级,是亚马逊为卖家提供的一种评估卖家账户健康状况的工具。通过AHR,亚马逊会对卖家的账户进行综合评估,并给出相应的评级,以反映账户的整体表现和信誉。
亚马…