在 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()));}}}
这时候就会交由 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.SpringBootMytestApplication
sourceClass =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.TestController
registry.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();}}}