本文只對IOC源碼(注解實(shí)現(xiàn))進(jìn)行深度解析葵礼,關(guān)于IOC的注解用法等讀者需查閱其他文檔罚缕。
下面所有的源碼解析將圍繞下面測試方法,代碼太多無法全部貼出來浮毯,只貼出關(guān)鍵代碼,讀者可自行進(jìn)入源碼一步步進(jìn)入查看泰鸡。
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MyConfig.class);
DemoService bean = ctx.getBean(DemoService.class);
System.out.println(ctx.getBean(DemoService.class));
}
首先债蓝,將斷點(diǎn)打在第一行代碼,進(jìn)入AnnotationConfigApplicationContext構(gòu)造器
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
1 this()方法
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
1.1 AnnotatedBeanDefinitionReader
作用是將spring內(nèi)部的bean定義信息(內(nèi)部的后置處理器)注冊到容器中,如ConfigurationClassPostProcessor盛龄、AutowiredAnnotationBeanPostProcessor的bean定義信息等
此處提一下beanDefinition和bean的區(qū)別:
beanDefinition:用于描述bean的信息饰迹,比如bean的構(gòu)造方法、參數(shù)讯嫂、是否懶加載等等
bean:所謂的實(shí)體類蹦锋,已經(jīng)初始化的對象
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
//bean定義注冊器,用于注冊所有的bean定義信息
this.registry = registry;
//condition注解的解析器欧芽,用于解析condition注解
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
//為容器注冊spring內(nèi)部的后置處理器莉掂,如ConfigurationClassPostProcessor、AutowiredAnnotationBeanPostProcessor等等
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
1.2 ClassPathBeanDefinitionScanner
作用是定義包掃描策略千扔。
public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,
Environment environment, ResourceLoader resourceLoader) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
//是否使用默認(rèn)的掃描策略,默認(rèn)true
if (useDefaultFilters) {
registerDefaultFilters();
}
setEnvironment(environment);
setResourceLoader(resourceLoader);
}
useDefaultFilters:是否使用spring默認(rèn)配置的掃描策略憎妙,默認(rèn)是true,進(jìn)入registerDefaultFilters()方法,發(fā)現(xiàn)可以掃描到basePackages路徑參數(shù)配置下所有配置Component注解的bean曲楚。
這就是為什么在使用includeFilters掃描過濾配置時(shí)厘唾,需在后面配置useDefaultFilters=false,否則會被默認(rèn)的配置覆蓋掉龙誊。
2 register(annotatedClasses)方法
作用是將自己寫的配置類注冊到容器中
public void registerBean(Class<?> annotatedClass, String name, Class<? extends Annotation>... qualifiers) {
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
}
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
abd.setScope(scopeMetadata.getScopeName());
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
for (Class<? extends Annotation> qualifier : qualifiers) {
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
3 refresh()方法(最為關(guān)鍵的一步!!!)
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 校驗(yàn)啟動容器所需參數(shù)并創(chuàng)造一個(gè)保存早期事件的集合
prepareRefresh();
// 獲取beanFactory容器
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 為容器注冊spring底層組件
prepareBeanFactory(beanFactory);
try {
// 1 模板方法抚垃,供子類調(diào)用,對BeanFactory進(jìn)行后置處理
postProcessBeanFactory(beanFactory);
// 2 執(zhí)行BeanFactory后置處理器趟大,將所有配置的bean定義信息注冊到容器中
invokeBeanFactoryPostProcessors(beanFactory);
// 3 注冊所有的BeanPostProcessor
registerBeanPostProcessors(beanFactory);
// 4 初始化國際化工具類MessageSource
initMessageSource();
// 5 初始化spring的事件多播器
initApplicationEventMulticaster();
// 6 開放式接口鹤树,供子類使用
onRefresh();
// 7 向容器中注冊事件發(fā)布的監(jiān)聽器
registerListeners();
// 8 創(chuàng)建和初始化所有bean
finishBeanFactoryInitialization(beanFactory);
// 9 發(fā)布事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
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;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
3.1 postProcessBeanFactory(beanFactory)
作用是定義了一個(gè)模板方法,供子類實(shí)現(xiàn)調(diào)用逊朽,用來對BeanFactory進(jìn)行后置處理罕伯。
3.2 invokeBeanFactoryPostProcessors(beanFactory)
作用是執(zhí)行BeanFactory后置處理器(BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor),將自己定義的bean的定義信息注冊到容器中叽讳。
附上流程圖
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// 將容器轉(zhuǎn)換成bean定義注冊器
Set<String> processedBeans = new HashSet<String>();
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<BeanDefinitionRegistryPostProcessor>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
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 = new ArrayList<BeanDefinitionRegistryPostProcessor>();
// 首先追他,執(zhí)行實(shí)現(xiàn) BeanDefinitionRegistryPostProcessors 接口且實(shí)現(xiàn)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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// 接著,執(zhí)行實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessors 接口且實(shí)現(xiàn)Ordered接口的后置處理器
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// 然后, 執(zhí)行只實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessors的后置處理器
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// 獲取所有實(shí)現(xiàn)BeanFactoryPostProcessor接口的后置處理器
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
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);
}
}
// 首先, 執(zhí)行實(shí)現(xiàn)了 BeanFactoryPostProcessors 接口且實(shí)現(xiàn)了PriorityOrdered接口的后置處理器
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// 然后,執(zhí)行實(shí)現(xiàn)了 BeanFactoryPostProcessors 接口且實(shí)現(xiàn)了Ordered接口的后置處理器
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// 最后, 執(zhí)行只實(shí)現(xiàn)了 BeanFactoryPostProcessors 接口的后置處理器
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
簡單的說就是執(zhí)行所有beanFactory后置處理器坟募,根據(jù)該后置處理器的優(yōu)先順序先后執(zhí)行而已。
先執(zhí)行實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor和PriorityOrdered接口的
再執(zhí)行實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor和Ordered接口的
再執(zhí)行實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor接口的
再執(zhí)行實(shí)現(xiàn)了BeanFactoryPostProcessor和PriorityOrdered接口的
再執(zhí)行實(shí)現(xiàn)了BeanFactoryPostProcessor和Ordered接口的
再執(zhí)行實(shí)現(xiàn)了BeanFactoryPostProcessor接口的
關(guān)鍵看invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry)方法(執(zhí)行后置處理器的方法)邑狸。由于ConfigurationClassPostProcessor在1中已經(jīng)注冊到容器中了懈糯,而且實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor和PriorityOrdered接口,所以優(yōu)先執(zhí)行此后置處理器推溃。下面就拿ConfigurationClassPostProcessor執(zhí)行后置處理器的方法源碼研究昂利,源碼進(jìn)入ConfigurationClassPostProcessor#processConfigBeanDefinitions
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<BeanDefinitionHolder>();
String[] candidateNames = registry.getBeanDefinitionNames();
//從容器中找到所有BeanDefinitionRegistryPostProcessor届腐,過濾出未執(zhí)行的后置處理器铁坎,即MainConfig配置類的BeanDefinitionRegistryPostProcessor
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;
}
// 將配置類根據(jù)order注解進(jìn)行排序
Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {
@Override
public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
}
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet && sbr.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
//componentScan掃描出來的bean的名字生成器
this.componentScanBeanNameGenerator = generator;
//import導(dǎo)入的bean的名字生成器
this.importBeanNameGenerator = generator;
}
}
// 創(chuàng)建配置類的解析器
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<BeanDefinitionHolder>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size());
do {
//解析配置類
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<ConfigurationClass>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
//將除了@Component注解注冊的bean外的其他方式注冊的bean定義注冊到容器中
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
candidates.clear();
//校驗(yàn)是否所有的bean定義信息已經(jīng)注冊完畢
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 bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null) {
if (!sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
從容器中找到自己寫的配置類,對其進(jìn)行parse解析犁苏。
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass);
// 解析@PropertySource 注解
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.warn("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) {
// 解析
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 needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
// 解析 @Import 注解
processImports(configClass, sourceClass, getImports(sourceClass), true);
// Process any @ImportResource annotations
if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// 解析 @Bean 注解
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// 處理接口
processInterfaces(configClass, sourceClass);
// 處理超類
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;
}
依此解析@PropertySource@ComponentScan@Import@ImportResource@Bean五個(gè)注解硬萍、接口、超類围详。由于常用@ComponentScan@Import兩個(gè)注解朴乖,下面只對解析@ComponentScan@Import的源碼分析
-1 解析@ComponentScan
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
//遍歷配置的basepackage路徑
for (String basePackage : basePackages) {
//找到路徑下所有Componet注解的組件
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
//注冊該當(dāng)前組件的bean定義信息到容器中
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
遍歷basePackage配置的路徑數(shù)組,找到路徑下的@Component注解注入的bean組件助赞,將該組件的bean定義注冊到容器中买羞。注意:這里只是注冊bean定義信息,并不是創(chuàng)建bean雹食。
-2 解析@Import
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, boolean checkForCircularImports) {
if (importCandidates.isEmpty()) {
return;
}
if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
for (SourceClass candidate : importCandidates) {
//判斷該組件是否實(shí)現(xiàn)了ImportSelector
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
Class<?> candidateClass = candidate.loadClass();
ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
ParserStrategyUtils.invokeAwareMethods(
selector, this.environment, this.resourceLoader, this.registry);
if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) {
this.deferredImportSelectors.add(
new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector));
}
//調(diào)用selectImports方法
else {
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
processImports(configClass, currentSourceClass, importSourceClasses, false);
}
}
////判斷該組件是否實(shí)現(xiàn)了ImportBeanDefinitionRegistrar
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
ParserStrategyUtils.invokeAwareMethods(
registrar, this.environment, this.resourceLoader, this.registry);
//將自己定義的bean定義添加到注冊器中 configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// 添加普通的import注解配置的bean定義信息到容器中
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass));
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}
處理@Import注解時(shí)畜普,并沒有直接將組件注冊到容器中,只是添加進(jìn)去群叶。
@Import注解配置bean有三種方式吃挑。
方法1:@Import(value = {Person.class, Car.class})
方法2:@Import(value = {MyImportSelector.class}),MyImportSelector必須實(shí)現(xiàn)ImportSelector接口街立,重寫selectImports方法舶衬,返回一個(gè)bean類路徑的數(shù)組。
public class MyImportSelector implements ImportSelector {
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[]{"com.testimport.compent.Dog"};
}
}
方法3:@Import(value = {MyBeanDefinitionRegister.class}),MyBeanDefinitionRegister必須實(shí)現(xiàn)ImportBeanDefinitionRegistrar接口赎离,重寫registerBeanDefinitions方法逛犹,在方法中注冊bean定義信息
public class MyBeanDefinitionRegister implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Cat.class);
registry.registerBeanDefinition("cat",rootBeanDefinition);
}
}
-3 解析@Bean注解
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
和@Import注解一樣,只是把配置類中@Bean注解的方法加進(jìn)去梁剔,并沒有將該組件的bean定義注冊到容器中虽画。
解析完所有組件,回到ConfigurationClassPostProcessor#processConfigBeanDefinitions方法的parse那行憾朴,此時(shí)@Component注解注冊的bean定義信息已經(jīng)注冊到容器中狸捕,但是@Import、@Bean注解等其他方式注冊的bean定義信息只是添加保存到各自集合中众雷,并沒有注冊灸拍。
接著做祝,進(jìn)入下面this.reader.loadBeanDefinitions(configClasses);那行,這里將注冊其他方式的bean定義信息鸡岗,進(jìn)入源碼混槐。
private void loadBeanDefinitionsForConfigurationClass(
ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
if (trackedConditionEvaluator.shouldSkip(configClass)) {
String beanName = configClass.getBeanName();
if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
this.registry.removeBeanDefinition(beanName);
}
this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
return;
}
//將@import注解注冊的bean定義信息注冊到容器中
if (configClass.isImported()) {
registerBeanDefinitionForImportedConfigurationClass(configClass);
}
//將@Bean注解注冊的bean定義信息注冊到容器中
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
loadBeanDefinitionsForBeanMethod(beanMethod);
}
//將@ImportedResources注解注冊的bean定義信息注冊到容器中 loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
//將實(shí)現(xiàn)BeanDefinitionRegistryPostProcessor接口注冊的bean定義信息注冊到容器中 loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}
此時(shí),@Import轩性、@Bean注解等注冊的bean定義信息已全部注冊到容器中
3.3 registerBeanPostProcessors(beanFactory)
作用是將所有的bean后置處理器注冊到容器中声登。
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//獲取所有beanPostProcessor(bean定義)
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// 獲取所有beanPostProcessor的數(shù)量
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 簡單的劃分,將后置處理器劃分到實(shí)現(xiàn)PriorityOrdered接口揣苏、Ordered接口悯嗓、其他普通的集合中
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
List<String> orderedPostProcessorNames = new ArrayList<String>();
List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// 注冊實(shí)現(xiàn)PriorityOrdered接口的bean后置處理器
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 注冊實(shí)現(xiàn)Ordered接口的bean后置處理器
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// 注冊其他沒有實(shí)現(xiàn)排序的后置處理器
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// 注冊spring內(nèi)部的后置處理器
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
依此注冊實(shí)現(xiàn)PriorityOrdered接口、實(shí)現(xiàn)Ordered接口卸察、未實(shí)現(xiàn)任何的脯厨、spring內(nèi)部的bean后置處理器。
3.4 initMessageSource()
作用是初始化一個(gè)工具類坑质,該工具類用來處理國際化合武。
3.5 initApplicationEventMulticaster()
作用是初始化spring事件多播器,此多播器用于向監(jiān)聽器廣播事件涡扼,使所有監(jiān)聽器(spring內(nèi)部的監(jiān)聽器和自己定義的實(shí)現(xiàn)ApplicationListener的監(jiān)聽器)稼跳,執(zhí)行onApplicationEvent(ApplicationEvent event)方法。
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//APPLICATION_EVENT_MULTICASTER_BEAN_NAME值是applicationEventMulticaster
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
判斷容器中是否有beanName是applicationEventMulticaster的多播器吃沪,如果有就獲取汤善,如果沒有就向容器中注冊一個(gè)beanName為applicationEventMulticaster的多播器。
3.6 onRefresh()
這是一個(gè)空方法巷波,一個(gè)開放式接口供子類調(diào)用萎津。在springBoot啟動tomcat時(shí)會調(diào)用這個(gè)方法。這里不做詳述抹镊。
3.7 registerListeners()
作用是向容器中注冊監(jiān)聽器锉屈。此處只是注冊監(jiān)聽器,并向監(jiān)聽器廣播早期事件垮耳;在后面3.9 finishRefresh()中調(diào)用publishEvent(new ContextRefreshedEvent(this))颈渊,向所有監(jiān)聽器廣播所有事件,包括自己定義發(fā)布的事件终佛。
protected void registerListeners() {
// 獲取3.5注冊的多播器俊嗽,向多播器中注冊spring內(nèi)部的監(jiān)聽器
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// 向多播器中注冊自己定義的實(shí)現(xiàn)ApplicationListener的監(jiān)聽器
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// 廣播早期事件
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
//獲取executor,如果支持異步調(diào)用铃彰,異步廣播事件绍豁,不支持就同步廣播事件
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
@Override
public void run() {
invokeListener(listener, event);
}
});
}
else {
invokeListener(listener, event);
}
}
}
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
//調(diào)用onApplicationEvent方法,執(zhí)行方法的業(yè)務(wù)代碼
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isDebugEnabled()) {
logger.debug("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
3.5和3.7的spring事件驅(qū)動模型牙捉,用到了觀察者模式竹揍,觀察者模式可以簡單的理解為發(fā)布-訂閱的模式敬飒,詳細(xì)內(nèi)容可查閱其他資料。
如果想支持異步廣播事件芬位,可以手動寫個(gè)類繼承SimpleApplicationEventMulticaster无拗,并取名為容器內(nèi)默認(rèn)的多播器名稱applicationEventMulticaster,此時(shí)容器在多播器初始化的時(shí)候就能找到我們自己建的這個(gè)多播器昧碉,并將多線程設(shè)置進(jìn)去英染,實(shí)現(xiàn)異步方式廣播。
@Component(value = "applicationEventMulticaster")
public class MyMulticaster extends SimpleApplicationEventMulticaster{
public MyMulticaster () {
setTaskExecutor(Executors.newSingleThreadExecutor());
}
}
3.8 inishBeanFactoryInitialization(beanFactory)
創(chuàng)建以及初始化bean
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
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));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
// 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);
}
// 設(shè)置類加載器到spring容器中
beanFactory.setTempClassLoader(null);
// 凍結(jié)配置被饿,到這邊為止四康,之后不能再修改bean定義信息
beanFactory.freezeConfiguration();
// 開始創(chuàng)建和初始化bean
beanFactory.preInstantiateSingletons();
}
public void preInstantiateSingletons() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//判斷是否是FactoryBean
if (isFactoryBean(beanName)) {
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 {
//開始創(chuàng)建bean
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
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();
}
}
}
}
調(diào)用AbstractBeanFactory的getBean方法開始創(chuàng)建bean,具體創(chuàng)建流程在4中會說
3.9 finishRefresh()
作用是完成容器刷新后的后續(xù)工作锹漱。清除緩存箭养、發(fā)布事件、初始化并刷新生命周期處理器哥牍。
protected void finishRefresh() {
// 初始化上下文生命周期處理器
initLifecycleProcessor();
// 刷新上下文生命周期處理器
getLifecycleProcessor().onRefresh();
// 發(fā)布事件
publishEvent(new ContextRefreshedEvent(this));
// 清除上下文資源緩存
LiveBeansView.registerApplicationContext(this);
}
4 getBean()解析
4.1 bean的生命周期
下面我們解析bean的生命周期,直接進(jìn)入關(guān)鍵方法doGetBean
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
//獲取別名喝检,
final String beanName = transformedBeanName(name);
Object bean;
// 從單例緩存池里獲取bean
Object sharedInstance = getSingleton(beanName);
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 = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// 判斷是否是多例的bean在創(chuàng)建嗅辣,如果是就拋錯(cuò)
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 檢查父工廠里有沒有bean
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) {
markBeanAsCreated(beanName);
}
try {
//根據(jù)別名獲取bean定義
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//檢查是否是抽象bean,抽象bean不能被實(shí)例化
checkMergedBeanDefinition(mbd, beanName, args);
// 檢查是否依賴其他的bean挠说,如果存在澡谭,就先創(chuàng)建依賴對象
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
//創(chuàng)建bean
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
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 {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + 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;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
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;
}
總的來說就是先從單例緩存池里獲取,如果有就直接獲取到bean返回损俭。如果沒有蛙奖,再從父工廠里獲取。如果再沒有杆兵,就自己創(chuàng)建一個(gè)雁仲,創(chuàng)建完后放入單例緩存池。
注:多例不走緩存池琐脏。
進(jìn)入創(chuàng)建bean源碼
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//設(shè)置當(dāng)前bean正在創(chuàng)建攒砖。在單例緩存池的判斷中會用到
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
//回調(diào)singletonFactory參數(shù)的getObject方法
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//將當(dāng)前對象移除正在創(chuàng)建的狀態(tài)
afterSingletonCreation(beanName);
}
if (newSingleton) {
//將創(chuàng)建的bean對象放入單例緩存池中
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
進(jìn)入回調(diào)的getObject方法,進(jìn)入createBean
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// 創(chuàng)建一個(gè)bean的代理對象,aop中用到日裙,這里只是將切面加到緩存中
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
//創(chuàng)建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//利用反射創(chuàng)建bean實(shí)例
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
mbd.resolvedTargetType = beanType;
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// 將早期對象放入單例緩存池
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);
}
});
}
//初始化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()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// 注冊銷毀bean的后置處理器
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
將早期對象加入到三級緩存中吹艇,以便循環(huán)依賴獲取此早期對象
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
//調(diào)用Aware接口
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//調(diào)用實(shí)現(xiàn)了BeanPostProcessor接口的postProcessBeforeInitialization方法
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//調(diào)用初始化方法
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()) {
//調(diào)用實(shí)現(xiàn)了BeanPostProcessor接口的postProcessAfterInitialization方法(aop中使用),這里會創(chuàng)建代理對象
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
初始化bean流程就是先調(diào)用(如果實(shí)現(xiàn)了Aware接口)實(shí)現(xiàn)Aware接口的bean的方法荒辕,然后調(diào)用(如果實(shí)現(xiàn)了BeanPostProcessor接口)實(shí)現(xiàn)BeanPostProcessor接口的postProcessBeforeInitialization方法蝴韭,然后調(diào)用初始化方法碘举,然后調(diào)用(如果實(shí)現(xiàn)了BeanPostProcessor接口)實(shí)現(xiàn)BeanPostProcessor接口的postProcessAfterInitialization方法。
這里說下bean初始化的多種方法鼻听。
方法1:自己定義初始化方法樟结,在注入容器的時(shí)候指定初始化方法
@Bean(initMethod = "init",destroyMethod = "destroy")
public Car car() {
return new Car();
}
方法2:通過 InitializingBean和DisposableBean 的二個(gè)接口實(shí)現(xiàn)bean的初始化化以及銷毀方法。
@Component
public class Person implements InitializingBean,DisposableBean {
public Person() {
System.out.println("Person的構(gòu)造方法");
}
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean的destroy()方法 ");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean的 afterPropertiesSet方法");
}
}
方法3:通過JSR250規(guī)范提供的注解@PostConstruct 和@ProDestory標(biāo)注的方法
@Component
public class Book {
public Book() {
System.out.println("book 的構(gòu)造方法");
}
@PostConstruct
public void init() {
System.out.println("book 的PostConstruct標(biāo)志的方法");
}
@PreDestroy
public void destory() {
System.out.println("book 的PreDestory標(biāo)注的方法");
}
}
方法4:通過Spring的BeanPostProcessor的 bean的后置處理器會攔截所有bean創(chuàng)建過程精算。源碼中可見postProcessBeforeInitialization在init前調(diào)用瓢宦,postProcessAfterInitialization在初始化后調(diào)用。
附上bean生命周期的圖
4.2 popularBean方法與循環(huán)依賴解決
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;
}
}
// 定義了一個(gè)開放接口InstantiationAwareBeanPostProcessor供我們調(diào)用灰羽,如果實(shí)現(xiàn)了該接口驮履,此處會調(diào)用該bean的before和after方法
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;
}
//獲取注入模式。
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 根據(jù)name注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 根據(jù)type注入
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);
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);
}
populateBean方法主要就是給bean所有屬性賦值廉嚼。
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
//獲取非簡單屬性玫镐,即bean屬性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
registerDependentBean(propertyName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
autowireByName方式注入。這里只是將屬性設(shè)置到緩存中怠噪,在后面進(jìn)行賦值
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
//解析非簡單屬性
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) {
return shortcut;
}
Class<?> type = descriptor.getDependencyType();
//解析@Value注解恐似,獲取值
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(strVal, bd);
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
//獲取容器中有幾個(gè)bean
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (matchingBeans.isEmpty()) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
//判斷數(shù)量是否大于一個(gè)
if (matchingBeans.size() > 1) {
//決定使用哪個(gè),根據(jù)哪個(gè)標(biāo)注了@Primary或@Priority注解就用哪個(gè)
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
//如果不能決定用哪個(gè)傍念,則判斷是否是必要的矫夷,如果是必要的就拋錯(cuò),如果不是必要的就返回空
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(type, matchingBeans);
}
else {
// In case of an optional Collection/Map, silently ignore a non-unique case:
// possibly it was meant to be an empty collection of multiple regular beans
// (before 4.3 in particular when we didn't even look for collection beans).
return null;
}
}
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
// We have exactly one match.
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
return (instanceCandidate instanceof Class ?
descriptor.resolveCandidate(autowiredBeanName, type, this) : instanceCandidate);
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
autowireByType需要判斷是否注入多個(gè)相同的bean憋槐,如果存在多個(gè)双藕,先判斷哪個(gè)上面標(biāo)了@Primary或@Priority注解,就使用哪個(gè)bean阳仔。如果沒有標(biāo)注忧陪,則判斷是否是必要的,在注入屬性的時(shí)候標(biāo)注@Autowired(required = false)就不是必要的近范,返回null嘶摊,沒有標(biāo)注required,默認(rèn)是true,會拋異常
下面進(jìn)入賦值階段
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs == null || pvs.isEmpty()) {
return;
}
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
if (pv.isConverted()) {
deepCopy.add(pv);
}
else {
String propertyName = pv.getName();
Object originalValue = pv.getValue();
//解析依賴
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// 這里才是給屬性賦值
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
下面是解析依賴的代碼评矩,如果是非簡單對象叶堆,會去獲取該對象的bean實(shí)例
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
String refName = ref.getBeanName();
refName = String.valueOf(doEvaluate(refName));
if (ref.isToParent()) {
if (this.beanFactory.getParentBeanFactory() == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Can't resolve reference to bean '" + refName +
"' in parent factory: no parent factory available");
}
return this.beanFactory.getParentBeanFactory().getBean(refName);
}
else {
//獲取依賴對象
Object bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
return bean;
}
}
catch (BeansException ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
}
}
這里會存在一個(gè)循環(huán)依賴的場景。
<bean id="instanceA" class="com.circulardependencies.InstanceA" >
<property name="instanceB" ref="instanceB"></property>
</bean>
<bean id="instanceB" class="com.circulardependencies.InstanceB" >
<property name="instanceA" ref="instanceA"></property>
</bean>
spring通過三級緩存解決了bean循環(huán)依賴的問題稚照。下面就是原理蹂空。
-1 首先創(chuàng)建instanceA對象。根據(jù)getBean流程果录,中間會有一塊將早期對象設(shè)置到三級緩存中上枕。在AbstractAutowireCapableBeanFactory的doCreateBean方法中。
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);
}
});
}
-2 接著就是調(diào)用populateBean方法弱恒,給instanceA屬性賦值辨萍,即給instanceB賦值,發(fā)現(xiàn)instanceB還未創(chuàng)建,此時(shí)需先創(chuàng)建instanceB對象锈玉,同樣的調(diào)用getBean方法爪飘,一直到創(chuàng)建完instanceB的早期對象,然后加到三級緩存中拉背。
-3 接著調(diào)用instanceB的populateBean方法师崎,給屬性賦值,即給instanceA賦值椅棺,此時(shí)又需要重新調(diào)用getBean方法獲取或創(chuàng)建instanceA犁罩。
-4 又進(jìn)入instanceA的getBean。我們在4.1中知道getBean都會先到單例緩存池緩存中拿两疚。在AbstractBeanFactory的doGetBean的方法中床估。
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
進(jìn)入getSIngleton。
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//從一級緩存中獲取bean诱渤,一般一級緩存存放的都是初始化后的完整的bean
Object singletonObject = this.singletonObjects.get(beanName);
// isSingletonCurrentlyInCreation,在創(chuàng)建的時(shí)候會將其設(shè)置為true丐巫,表示對象正在創(chuàng)建中
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);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
這里解釋下三級緩存勺美。
一級緩存:singletonObject
二級緩存:earlySingletonObjects
三級緩存:singletonFactories
由于一開始在創(chuàng)建instanceA的時(shí)候递胧,已經(jīng)將早期對象放到三級緩存中,所以這里可以直接獲取到励烦,返回instanceA谓着。
-5 此時(shí)instanceB的屬性instanceA已經(jīng)賦值完成,返回坛掠,按照4.1中創(chuàng)建bean流程,將instanceB創(chuàng)建完成治筒。
-6 接著返回到第二步屉栓,將創(chuàng)建好的instanceB賦值到instanceA中依賴的instanceB屬性。再走完剩下的初始化流程耸袜,完成instanceA的創(chuàng)建友多。
我們可以發(fā)現(xiàn),如果沒有緩存堤框,那么A和B將無限循環(huán)創(chuàng)建域滥,報(bào)錯(cuò)。所以我們可以得出以下兩個(gè)結(jié)論蜈抓。
-1 多例的bean無法解決循環(huán)依賴的問題启绰。因?yàn)槎嗬蛔呔彺妗?br>
-2 構(gòu)造器方式注入bean無法解決循環(huán)依賴問題。因?yàn)閺?.1中看出沟使,構(gòu)造器方式注入的bean委可,在暴露早期對象之前就已經(jīng)通過構(gòu)造器方式創(chuàng)建bean實(shí)例,發(fā)現(xiàn)需要依賴instanceB對象腊嗡,并沒有進(jìn)入到下面的將instanceA的早期對象實(shí)例放入緩存的那一步着倾。
@Bean
public InstanceA instanceA(InstanceB instanceB){
return new InstanceA(instanceB);
}
@Bean
public InstanceB instanceB(InstanceA instanceA) {
return new InstanceB(instanceA);
}
上面就是構(gòu)造器方式注入bean拾酝,無法解決循環(huán)依賴。
IOC的源碼解析介紹到此結(jié)束卡者,如有分析不到位蒿囤,敬請諒解!!!