Spring源码逻辑梳理

一. 调用this()无参构造方法去实例化AnnotatedBeanDefinitionReader(初始化创世类)和ClassPathBeanDefinitionScanner(手动调用才会用到)

二. 调用register(annotatedClasses)去将我们传入的配置类注册进beanDefinitionMap

三. 调用refresh() 进行bean的初始化

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}

1. prepareRefresh()方法进行刷新上下文,主要是对启动事件,活动状态等进行初始化

2. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory() 获取新的bean工厂

3. prepareBeanFactory(beanFactory); 将获取到的bean工厂覆盖当前Context

4. postProcessBeanFactory(beanFactory); 对bean工厂进行处理,进去里面是空实现,可能是为了扩展。

5. invokeBeanFactoryPostProcessors(beanFactory); 执行bean工厂的所有后置处理器

代码量太大,调用链过深,接下来我只会把主要代码贴上来或代码分段,建议自己对比者源码看
还有一个注意点:Component注解也会当做配置类,但是并不会为其生成CGLIB代理Class,所以下面解析配
类时会解析到是正常的,@Configuration标注的会被指定属性为Full意为完整配置类,其它为不完整配置类

这一块代码主要执行的是spring自己的bean工厂处理器,执行完后,会将所有该配置到的beanDifinition找到

		//执行过的后置处理器Set
		Set<String> processedBeans = new HashSet<String>();
//判断bean工厂是否有实现BeanDefinitionRegistry这个类,这个结果为true直接进入
if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//常规的bean工厂的后置处理器集合
			List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
			//带注册功能的bean工厂后置处理器集合
			List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
					new LinkedList<BeanDefinitionRegistryPostProcessor>();

			//beanFactoryPostProcessors 一直为0,只有调用其它方式初始化 这个逻辑才会执行 所以可忽略这个循环
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {				
			}
			//得到所有实现了BeanDefinitionRegistryPostProcessor接口的类,即我们前面添加的创世类
			//注意得到的其实是从beanDifinitionMap里取到的
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

			// 第一步,执行所有实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					//标明当前后置处理器执行过了
					processedBeans.add(ppName);
				}
			}
			//进行排序
			OrderComparator.sort(priorityOrderedPostProcessors);
			//将得到的集合注册进上面的集合里
			registryPostProcessors.addAll(priorityOrderedPostProcessors);
			//执行符合条件的带注册的后置处理器集合
			invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

			// 第二步与第一步一样的逻辑,不过筛选掉的是未实现Ordered接口与执行过的类
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
			for (String ppName : postProcessorNames) {
				//晒选掉执行过的,与没有实现Ordered接口的
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			OrderComparator.sort(orderedPostProcessors);
			registryPostProcessors.addAll(orderedPostProcessors);
			invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

			//第三步,调用其它所有的带注册的bean工厂的后置处理器
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {
					if (!processedBeans.contains(ppName)) {
						BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
						registryPostProcessors.add(pp);
						processedBeans.add(ppName);
						pp.postProcessBeanDefinitionRegistry(registry);
						reiterate = true;
					}
				}
			}

			// 第四步,调用bean工厂后置处理器的方法,可能会疑惑为什么带注册功能的bean工厂后置处理器也会被调用,
			//那是因为带注册功能的bean工厂后置处理器是继承自不带注册功能的bean工厂后置处理器的
			invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

下面才是执行我们自定义的后置处理器

//获取直接或间接实现BeanFactoryPostProcessor接口的后置处理器类名称集合
String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		//优先排序的后置处理器集合
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		//排序的后置处理器集合
		List<String> orderedPostProcessorNames = new ArrayList<String>();
		//没有排序的后置处理器集合
		List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			}
			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			}
			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			}
			else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		OrderComparator.sort(priorityOrderedPostProcessors);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		OrderComparator.sort(orderedPostProcessors);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

总结:我将这个方法分为两大步骤
1.调用Spring自己的东西解析我们配置的内容
2.调用我们自己定义的beanFactoryPostProcessors
它们都按照 PriorityOrdered>Ordered>nonOrdered

接下来我们进入
invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);
再进入到ConfigurationClassPostProcessor类的postProcessBeanDefinitionRegistry方法

@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		//初始化了一个bean定义
		RootBeanDefinition iabpp = new RootBeanDefinition(ImportAwareBeanPostProcessor.class);
		//标明该bean定义属于spring后台使用
		iabpp.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		//注册
		registry.registerBeanDefinition(IMPORT_AWARE_PROCESSOR_BEAN_NAME, iabpp);
		//同上
		RootBeanDefinition ecbpp = new RootBeanDefinition(EnhancedConfigurationBeanPostProcessor.class);
		ecbpp.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
		registry.registerBeanDefinition(ENHANCED_CONFIGURATION_PROCESSOR_BEAN_NAME, ecbpp);

		//这里的逻辑是记录配置类的后置处理器在那个工厂里面注册过了,如果再注册就报错,个人观点,如有错误请提示
		//获取唯一标识
		int registryId = System.identityHashCode(registry);
		//查看在带注册的工厂后置处理器里是否已经解析过
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		//查看工厂后置处理器里是否已经解析过
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		//标识已经解析过
		this.registriesPostProcessed.add(registryId);

		//执行配置bean定义(解析bean定义)
		processConfigBeanDefinitions(registry);
	}

进入processConfigBeanDefinitions(registry);

	public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		//配置获选人
		Set<BeanDefinitionHolder> configCandidates = new LinkedHashSet<BeanDefinitionHolder>();
		//得到当前已经注册的bean定义
		String[] candidateNames = registry.getBeanDefinitionNames();

		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			//判断是否解析过了(即已注册未解析)
			if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
					ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			//检查是否配置类
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// Return immediately if no @Configuration classes were found
		if (configCandidates.isEmpty()) {
			return;
		}

		// 得到bean的名称生成器,如果有设置自定义的BeanName生成器则调用
		SingletonBeanRegistry singletonRegistry = null;
		if (registry instanceof SingletonBeanRegistry) {
			singletonRegistry = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet && singletonRegistry.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
				BeanNameGenerator generator = (BeanNameGenerator) singletonRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
				this.componentScanBeanNameGenerator = generator;
				this.importBeanNameGenerator = generator;
			}
		}

		// Parse each @Configuration class 解析每个配置类
		//metadataReaderFactory:元数据阅读器工厂
		//problemReporter:问题记录者
		//environment:环境
		//resourceLoader:资源加载器
		//componentScanBeanNameGenerator:组件名称生成器
		//registry:beanDifinitionRegister
		ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

		//已经解析的配置类
		Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size());
		do {
			//解析,可以跳到下面再回头看这个
			parser.parse(configCandidates);
			//验证配置类对象
			parser.validate();
			//获取上面解析到的类
			Set<ConfigurationClass> configClasses = new LinkedHashSet<ConfigurationClass>(parser.getConfigurationClasses());
			//移除已经解析过的类
			configClasses.removeAll(alreadyParsed);
			
			//读取模型并创建beandefinition集
			// Read the model and create bean definitions based on its content
			if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(registry, this.sourceExtractor,
						this.problemReporter, this.metadataReaderFactory, this.resourceLoader, this.environment,
						this.importBeanNameGenerator, parser.getImportRegistry());
			}
			//将配置类读取成beanDefinition
			this.reader.loadBeanDefinitions(configClasses);
			alreadyParsed.addAll(configClasses);
			//清空配置获选集合
			configCandidates.clear();
			if (registry.getBeanDefinitionCount() > candidateNames.length) {
				String[] newCandidateNames = registry.getBeanDefinitionNames();
				Set<String> oldCandidateNames = new HashSet<String>(Arrays.asList(candidateNames));
				Set<String> alreadyParsedClasses = new HashSet<String>();
				for (ConfigurationClass configurationClass : alreadyParsed) {
					alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
				}
				for (String candidateName : newCandidateNames) {
					if (!oldCandidateNames.contains(candidateName)) {
						BeanDefinition beanDef = registry.getBeanDefinition(candidateName);
						if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory) &&
								!alreadyParsedClasses.contains(beanDef.getBeanClassName())) {
							configCandidates.add(new BeanDefinitionHolder(beanDef, candidateName));
						}
					}
				}
				candidateNames = newCandidateNames;
			}
		}
		while (!configCandidates.isEmpty());

		// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
		if (singletonRegistry != null) {
			if (!singletonRegistry.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
				singletonRegistry.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
			}
		}

		if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
			((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
		}
	}

parser.parse(configCandidates);跳过中间的逻辑直接进到protected void processConfigurationClass(ConfigurationClass configClass)方法

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
			return;
		}

		//配置类缓存中是否已有该配置类
		ConfigurationClass existingClass = this.configurationClasses.get(configClass);
		if (existingClass != null) {
			//检查配置类是否是通过Import或嵌套在另一个配置类中而注册导入的
			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);
				for (Iterator<ConfigurationClass> it = this.knownSuperclasses.values().iterator(); it.hasNext(); ) {
					if (configClass.equals(it.next())) {
						it.remove();
					}
				}
			}
		}

		//递归执行解析配置类及其父类层次结构
		SourceClass sourceClass = asSourceClass(configClass);
		do {
			//真正执行解析配置类
			sourceClass = doProcessConfigurationClass(configClass, sourceClass);
		}
		while (sourceClass != null);
		//将该配置类假如配置类集合中
		this.configurationClasses.put(configClass, configClass);
	}

doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) 方法

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		// Recursively process any member (nested) classes first
		//首先递归处理任何成员(嵌套)类 ,内部类之类的
		processMemberClasses(configClass, sourceClass);

		//处理@PropertSource注解
		// Process any @PropertySource annotations
		@PropertSource:执行加载指定的属性文件
		for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), PropertySources.class, org.springframework.context.annotation.PropertySource.class)) {
			if (this.environment instanceof ConfigurableEnvironment) {
				//执行解析propertySource注解,调用链太深了,感兴趣的自己进去看看
				processPropertySource(propertySource);
			}
			else {
				logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
						"]. Reason: Environment must implement ConfigurableEnvironment");
			}
		}


		//处理@ComponentScan 注解
		// Process any @ComponentScan annotations
		AnnotationAttributes componentScan = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ComponentScan.class);
		if (componentScan != null && !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			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 necessary
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), this.metadataReaderFactory)) {
					parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
				}
			}
		}
		
		//处理@Import 注解
		// Process any @Import annotations
		processImports(configClass, sourceClass, getImports(sourceClass), true);
		
		//处理@ImportResource 注解
		// Process any @ImportResource annotations
		if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
			AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
			String[] resources = importResource.getStringArray("value");
			Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
			for (String resource : resources) {
				String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
				configClass.addImportedResource(resolvedResource, readerClass);
			}
		}

		//处理单个Bean方法
		// Process individual @Bean methods
		Set<MethodMetadata> beanMethods = sourceClass.getMetadata().getAnnotatedMethods(Bean.class.getName());
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}

		//处理父类,如果有的话
		// Process superclass, if any
		if (sourceClass.getMetadata().hasSuperClass()) {
			String superclass = sourceClass.getMetadata().getSuperClassName();
			if (!superclass.startsWith("java") && !this.knownSuperclasses.containsKey(superclass)) {
				this.knownSuperclasses.put(superclass, configClass);
				// Superclass found, return its annotation metadata and recurse
				return sourceClass.getSuperClass();
			}
		}

		//没有父类,解析完成
		// No superclass -> processing is complete
		return null;
	}

6. registerBeanPostProcessors(beanFactory); 注册bean工厂的后置处理器

7. initMessageSource(); 国际化处理

8. initApplicationEventMulticaster();初始化事件多播器

9. onRefresh();初始化特定上下文的其它特殊beans, 空实现

10. finishBeanFactoryInitialization(beanFactory); registerListeners(); 检查事件监听器并注册它们

11. finishBeanFactoryInitialization(beanFactory);实例化所有剩余的(非延迟初始化)单例。

进入finishBeanFactoryInitialization方法

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
		// 为上下文初始化转换服务
		if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
				beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
			beanFactory.setConversionService(
					beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
		}

		//TODO:初始化加载时感知,暂时不知道它是干嘛的,后面有时候再看一下
		// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
		String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
		for (String weaverAwareName : weaverAwareNames) {
			getBean(weaverAwareName);
		}

		// 停止使用临时类加载器
		beanFactory.setTempClassLoader(null);

		// 允许缓存所有的bean定义元数据,不需要更改
		beanFactory.freezeConfiguration();

		//实例化所有剩余的(非延迟初始化)单例
		beanFactory.preInstantiateSingletons();
	}

接着进入preInstantiateSingletons();

	@Override
	public void preInstantiateSingletons() throws BeansException {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Pre-instantiating singletons in " + this);
		}

		//利用已经解析好的bean定义名称集去实例化一个新的集合
		List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

		// 实例化所有非懒加载的单例bean
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			//判断该bean定义是否接口,单例,懒加载
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				//判断是否是工厂bean
				if (isFactoryBean(beanName)) {
					//取到原始bena
					final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
					//是否急于初始化
					boolean isEagerInit;
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
							@Override
							public Boolean run() {
								return ((SmartFactoryBean<?>) factory).isEagerInit();
							}
						}, getAccessControlContext());
					}
					else {
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					if (isEagerInit) {
						getBean(beanName);
					}
				}
				else {
					//非工厂bean初始化
					getBean(beanName);
				}
			}
		}

		// 在所有的bean初始化完后,判段bean是否实现了SmartInitializingSingleton 接口,如果实现的化则调用
		//afterSingletonsInstantiated()接口
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged(new PrivilegedAction<Object>() {
						@Override
						public Object run() {
							smartSingleton.afterSingletonsInstantiated();
							return null;
						}
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

在进入getBean()方法前先看一下getSingleton(),这个方法很重要,涉及到bean的循环依赖解决

protected Object getSingleton(String beanName, boolean allowEarlyReference) {
		//一级缓存池存的是成熟态对象,即完全创建好的对象
		//二级缓存池存的是纯静态对象,即提前创建的单例对象,存放原始的 bean 对象(尚未填充属性)
		//三级缓存池存的是单例对象工厂的接口集(即一个单例工厂,调用方法可得到一个对象,以下简称为函数式接口)
		
		//从一级缓存池里取对象
		Object singletonObject = this.singletonObjects.get(beanName);
		//判断一级缓存池里没有该对象,而该对象正在创建
		if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
			synchronized (this.singletonObjects) {
				//从二级缓存池里取
				singletonObject = this.earlySingletonObjects.get(beanName);
				//二级缓存池也还是没有
				if (singletonObject == null && allowEarlyReference) {
					//从三级缓存池((函数式接口缓存池)里取
					ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
					if (singletonFactory != null) {
						//调用函数式接口得到一个单例对象
						singletonObject = singletonFactory.getObject();
						//把该对象加入到二级缓存池里
						this.earlySingletonObjects.put(beanName, singletonObject);
						//将该对象从三级缓存池里移除
						this.singletonFactories.remove(beanName);
					}
				}
			}
		}
		//判断值在三级缓存里是否存在,不存在返回Null
		return (singletonObject != NULL_OBJECT ? singletonObject : null);
	}

接着进入getBean(),一直跳到doGetBean()方法

protected <T> T doGetBean(
			final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
			throws BeansException {
		//得到规范的名称,比如去除工厂引用前缀或将别名解析成真正的bean名称
		final String beanName = transformedBeanName(name);
		Object bean;

		// 先检查三级缓存池是否有注册了该单例对象2
		Object sharedInstance = getSingleton(beanName);
		//如果有的话,则执行,一般没有,直接进下面的else逻辑
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			//得到一个bean对象
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			//判断bean是否在创建,如果是的话我们正在循环依赖中
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// todo:得到父bean工厂好像是为了集成其它框架准备的,我后面用其它框架试一下,默认为空,Skip
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				String nameToLookup = originalBeanName(name);
				if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			if (!typeCheckOnly) {
				//标记Bean正在创建
				markBeanAsCreated(beanName);
			}

			try {
				//得到合并的本地bean定义,即RootBeanDefinition 
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				//简称bean定义是否规范,里面简单的判断类是否是抽象的
				checkMergedBeanDefinition(mbd, beanName, args);

				// 得到当前Bean所需要依赖的bean集合
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					for (String dependsOnBean : dependsOn) {
						if (isDependent(beanName, dependsOnBean)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
						}
						registerDependentBean(dependsOnBean, beanName);
						getBean(dependsOnBean);
					}
				}

				// 创建bean单例
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						@Override
						public Object getObject() throws BeansException {
							try {
								//钩子方法,执行创建Bean,重点
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					//得到bean对象,只所以再次调用这个获取bean可能就是因为是统一的得到规范bean的接口吧
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					//它是一个多例,没什么好说的
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				else {
					//得到bean定义的作用范围
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
					}
					try {
						Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
							@Override
							public Object getObject() throws BeansException {
								beforePrototypeCreation(beanName);
								try {
									return createBean(beanName, mbd, args);
								}
								finally {
									afterPrototypeCreation(beanName);
								}
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; " +
								"consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		//检查所需类型是否与得到的bean类型匹配
		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
			try {
				return getTypeConverter().convertIfNecessary(bean, requiredType);
			}
			catch (TypeMismatchException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Failed to convert bean '" + name + "' to required type [" +
							ClassUtils.getQualifiedName(requiredType) + "]", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

进入createBean(beanName, mbd, args)方法

@Override
	protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
			throws BeanCreationException {

		if (logger.isDebugEnabled()) {
			logger.debug("Creating instance of bean '" + beanName + "'");
		}
		//确保是否真正的解析了Bean类,不得不说是真牛逼,源码考虑的是真的全面!就是看的有点累
		// Make sure bean class is actually resolved at this point.
		resolveBeanClass(mbd, beanName);

		//执行方法覆盖
		try {
			mbd.prepareMethodOverrides();
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
					beanName, "Validation of method overrides failed", ex);
		}

		try {
			//让 <b>BeanPostProcessors</b> 有机会返回一个代理而不是目标 bean 实例
			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
			Object bean = resolveBeforeInstantiation(beanName, mbd);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		//真正执行创建bean
		Object beanInstance = doCreateBean(beanName, mbd, args);
		if (logger.isDebugEnabled()) {
			logger.debug("Finished creating instance of bean '" + beanName + "'");
		}
		return beanInstance;
	}

进入createBean的第一个重点方法resolveBeforeInstantiation(beanName, mbd);

	protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			//判断是否是合成的 And 有实例化感知的bean后置处理器
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				//确认目标bean类型
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
					//里面调用逻辑很简单,就是判断是否实现了对应的接口,如果实现了则直接调用后置处理器的方法
					//在实例化之前应用 Bean 后处理器
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
						//在实例化之后应用 Bean 后处理器
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			//标识bean定义的beforeInstantiationResolved 状态,true表示在实例化之前创建
			mbd.beforeInstantiationResolved = (bean != null);
		}
		//返回bean
		return bean;
	}

进入createBean的第二个重点方法 doCreateBean(beanName, mbd, args);

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// Instantiate the bean.
		//bean的包装器
		BeanWrapper instanceWrapper = null;
		//是否单例
		if (mbd.isSingleton()) {
			//工厂bean缓存池移除该bean
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			//创建一个bean实例
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
		Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

		//允许后处理器修改合并的 bean 定义。即@AutoWired @Value
		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				//执行合并的bean定义后置处理器
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				mbd.postProcessed = true;
			}
		}

		// Eagerly cache singletons to be able to resolve circular references
		// even when triggered by lifecycle interfaces like BeanFactoryAware.
		//添加到三级缓存,以便想要先创建对象时使用
		boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
				isSingletonCurrentlyInCreation(beanName));
		if (earlySingletonExposure) {
			if (logger.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, new ObjectFactory<Object>() {
				@Override
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

		// 初始化对象
		Object exposedObject = bean;
		try {
			//填充bean,即属性赋值
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				//初始化bean
				exposedObject = initializeBean(beanName, exposedObject, mbd);
			}
		}
		catch (Throwable ex) {
			if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
				throw (BeanCreationException) ex;
			}
			else {
				throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
			}
		}

		if (earlySingletonExposure) {
			Object earlySingletonReference = getSingleton(beanName, false);
			if (earlySingletonReference != null) {
				if (exposedObject == bean) {
					exposedObject = earlySingletonReference;
				}
				else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
					String[] dependentBeans = getDependentBeans(beanName);
					Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
					for (String dependentBean : dependentBeans) {
						if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
							actualDependentBeans.add(dependentBean);
						}
					}
					if (!actualDependentBeans.isEmpty()) {
						//抛出了异常,太长了我删掉了
					}
				}
			}
		}

		// Register bean as disposable.
		try {
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}
  1. 创建bean实例
  2. 填充属性populateBean
	protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		PropertyValues pvs = mbd.getPropertyValues();

		if (bw == null) {
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
			}
			else {
				// Skip property population phase for null instance.
				return;
			}
		}

		// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
		// state of the bean before properties are set. This can be used, for example,
		// to support styles of field injection.
		boolean continueWithPropertyPopulation = true;
		//属性赋值工厂后置处理器调用
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}
		//如果想要停止赋值
		if (!continueWithPropertyPopulation) {
			return;
		}
		//是否按AUTOWIRE_BY_NAME OR AUTOWIRE_BY_TYPE方式定义的
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			//根据名称自动装配属性的值
			// Add property values based on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			//根据类型自动装配属性的值
			// Add property values based on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
			//注入属性PropertyValues @AutoWired在这里解析
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}
		//执行属性赋值
		applyPropertyValues(beanName, mbd, bw, pvs);
	}
  1. 初始化
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					invokeAwareMethods(beanName, bean);
					return null;
				}
			}, getAccessControlContext());
		}
		else {
			//执行各种aware方法 BeanNameAware BeanClassLoaderAware BeanFactoryAware
			invokeAwareMethods(beanName, bean);
		}
 
		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			//初始化前调用
			wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
		}

		try {
			//执行初始化方法
			invokeInitMethods(beanName, wrappedBean, mbd);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(
					(mbd != null ? mbd.getResourceDescription() : null),
					beanName, "Invocation of init method failed", ex);
		}

		if (mbd == null || !mbd.isSynthetic()) {
			//初始化执行后,AOP动态代理实现位置
			wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
		}
		//返回包装bean
		return wrappedBean;
	}

12. inishRefresh(); 最后一步,结束刷新,并发布对应的事件

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架的源码逻辑非常复杂,涉及到很多模块和组件。以下是大致的Spring源码逻辑: 1. 核心容器:Spring框架的核心是容器,主要包括BeanFactory和ApplicationContext。BeanFactory是Spring的基础容器,负责管理和创建Bean对象。ApplicationContext是BeanFactory的子接口,提供了更多的功能,如国际化、事件驱动等。 2. Bean的加载和解析:Spring通过XML配置文件或注解等方式定义Bean的配置信息。在容器启动时,会解析配置文件或扫描注解,将Bean的定义加载到容器中。 3. Bean的创建和初始化:容器根据Bean的定义信息,通过反射机制创建Bean对象,并进行属性注入和依赖注入。同时,Spring提供了一些扩展点(如BeanPostProcessor、InitializingBean接口等),可以在Bean创建和初始化的过程中进行自定义操作。 4. AOP(面向切面编程):Spring框架支持AOP,通过代理机制实现对方法的增强或拦截。在AOP模块中,涉及到切点、通知、切面等概念。 5. 事务管理:Spring提供了事务管理的支持,可以通过声明式事务或编程式事务来管理数据库事务。在事务模块中,涉及到事务定义、事务切面、事务管理器等。 6. MVC(模型-视图-控制器):Spring MVC是Spring框架中的Web开发模块,提供了灵活的Web应用程序开发方式。涉及到控制器、视图解析器、处理器映射等。 以上是Spring源码的高层逻辑,实际上,Spring框架由众多模块组成,每个模块负责不同的功能。Spring源码逻辑非常庞大且复杂,需要深入研究和理解才能掌握和使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值