SpringIOC
2021-08-19 15:05:42 0 举报
AI智能生成
Spring IOC 源码脑图
作者其他创作
大纲/内容
AbstractApplicationContext
ClassPathXmlApplicationContext
refresh();
obtainFreshBeanFactory()
AnnotationConfigApplicationContext
创建Bean工厂 BeanFactory
DefaultListableBeanFactory 注意实现了Bean定义注册器 BeanDefinitionRegistry
DefaultListableBeanFactory 注意实现了Bean定义注册器 BeanDefinitionRegistry
创建Bean定义读取器 BeanDefinitionReader(AnnotatedBeanDefinitionReader)
beanDefs.add -> ConfigurationClassPostProcessor
beanDefs.add -> AutowiredAnnotationBeanPostProcessor
beanDefs.add -> CommonAnnotationBeanPostProcessor
beanDefs.add -> EventListenerMethodProcessor
beanDefs.add -> DefaultEventListenerFactory
创建Bean定义扫描器 BeanDefinitionScanner(ClassPathBeanDefinitionScanner)
注册传入的配置类 register(componentClasses); -> reader.register(componentClasses);
refresh();
obtainFreshBeanFactory();
refreshed=true
beanFactory.setSerializationId
return beanFactory;
invokeBeanFactoryPostProcessors(beanFactory);
BeanDefinitionRegistryPostProcessor
PriorityOrdered
postProcessBeanDefinitionRegistry
PriorityOrdered
postProcessBeanDefinitionRegistry
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
ConfigurationClassPostProcessor
processConfigBeanDefinitions
ConfigurationClassPostProcessor
processConfigBeanDefinitions
configCandidates
ConfigurationClassUtils.checkConfigurationClassCandidate
ConfigurationClassUtils.checkConfigurationClassCandidate
configCandidates -> do…while
ConfigurationClassParser.parse(candidates);
doProcessConfigurationClass
@Component -> processMemberClasses
@PropertySource -> processPropertySource
@ComponentScan
componentScanParser.parse
scanner.doScan(basePackages);
findCandidateComponents
scanCandidateComponents
getResources(packageSearchPath)
isCandidateComponent
registerBeanDefinition
beanDefinitionNames.add(beanName);
beanDefinitionNames.add(beanName);
ConfigurationClassUtils.checkConfigurationClassCandidate
ConfigurationClassParser.parse(candidates);
ConfigurationClassParser.parse(candidates);
@Import -> processImports
@ImportResource -> configClass.addImportedResource
@Bean -> retrieveBeanMethodMetadata
interfaces -> processInterfaces
superclass -> knownSuperclasses.put(superclass, configClass);return sourceClass.getSuperClass();
configClasses=parser.getConfigurationClasses();
reader.loadBeanDefinitions(configClasses);
newCandidateNames = registry.getBeanDefinitionNames() - candidateNames;
ConfigurationClassUtils.checkConfigurationClassCandidate(newCandidateBeanDefinition);
configCandidates -> ConfigurationClassParser.parse(candidates);
BeanDefinitionRegistryPostProcessor
Ordered
postProcessBeanDefinitionRegistry
Ordered
postProcessBeanDefinitionRegistry
BeanDefinitionRegistryPostProcessor
postProcessBeanDefinitionRegistry
postProcessBeanDefinitionRegistry
BeanDefinitionRegistryPostProcessor
postProcessBeanFactory
postProcessBeanFactory
enhanceConfigurationClasses
传入的配置类会被CGLIB代理,对类内部对象进行getBean
传入的配置类会被CGLIB代理,对类内部对象进行getBean
BeanFactoryPostProcessor
(AbstractApplicationContext.beanFactoryPostProcessors用context.add才有)
postProcessBeanFactory
(AbstractApplicationContext.beanFactoryPostProcessors用context.add才有)
postProcessBeanFactory
BeanFactoryPostProcessor
PriorityOrdered
postProcessBeanFactory
PriorityOrdered
postProcessBeanFactory
BeanFactoryPostProcessor
Ordered
postProcessBeanFactory
Ordered
postProcessBeanFactory
BeanFactoryPostProcessor
postProcessBeanFactory
postProcessBeanFactory
finishBeanFactoryInitialization(beanFactory);
beanFactory.freezeConfiguration();
beanFactory.preInstantiateSingletons();
List<String> beanNames=new ArrayList<>(this.beanDefinitionNames);
RootBeanDefinition bd=getMergedLocalBeanDefinition(beanName);
!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()
非抽象、单例、非懒加载
非抽象、单例、非懒加载
isFactoryBean(beanName)
是否为工厂Bean
是否为工厂Bean
getBean(beanName);
String beanName=transformedBeanName(name);
getSingleton(beanName);
-> getSingleton(beanName,true)
缓存检查
-> getSingleton(beanName,true)
缓存检查
getSingleton(beanName,allowEarlyReference)
singletonObjects.get(beanName);
从一级缓存拿对象没有
从一级缓存拿对象没有
isSingletonCurrentlyInCreation(beanName)
一级缓存为空看是否正在创建
singletonsCurrentlyInCreation.contains(beanName);
一级缓存为空看是否正在创建
singletonsCurrentlyInCreation.contains(beanName);
earlySingletonObjects.get(beanName);
一级缓存没有且正在创建,检查二级缓存
一级缓存没有且正在创建,检查二级缓存
allowEarlyReference=true (resolving a circular reference)
二级缓存没有 且 允许早期引用当前创建的单例
二级缓存没有 且 允许早期引用当前创建的单例
synchronized(singletonObjects)
singletonObjects.get(beanName)
检查一级缓存没有
检查一级缓存没有
earlySingletonObjects.get(beanName)
检查二级缓存没有
检查二级缓存没有
ObjectFactory<?> singletonFactory=singletonFactories.get(beanName);
singletonObject=singletonFactory.getObject();
从三级缓存取出来函数接口创建实例
singletonObject=singletonFactory.getObject();
从三级缓存取出来函数接口创建实例
earlySingletonObjects.put(beanName, singletonObject);
放到二级缓存中
放到二级缓存中
singletonFactories.remove(beanName);
从三级缓存移除
从三级缓存移除
isPrototypeCurrentlyInCreation(beanName)
若在创建中,则 throw BeanCurrentlyInCreationException
Spring 只能解决单例对象的 setter 注入的循环依赖,不能解决构造器注入。
若在创建中,则 throw BeanCurrentlyInCreationException
Spring 只能解决单例对象的 setter 注入的循环依赖,不能解决构造器注入。
parentBeanFactory.getBean
有父容器,则检查父容器
有父容器,则检查父容器
!typeCheckOnly -> markBeanAsCreated(beanName);
typeCheckOnly:是否获取实例是为了进行类型检查,而不是为了实际使用
标记bean被创建了或者正要被创建
typeCheckOnly:是否获取实例是为了进行类型检查,而不是为了实际使用
标记bean被创建了或者正要被创建
String[] dependsOn=mbd.getDependsOn();
解析依赖Bean,若有则先创建依赖的Bean
解析依赖Bean,若有则先创建依赖的Bean
registerDependentBean(dep, beanName);
getBean(dep);
mbd.isSingleton()
sharedInstance=getSingleton(beanName,() -> {
createBean(beanName,mergedBeanDefinition,args);
});
createBean(beanName,mergedBeanDefinition,args);
});
getSingleton(beanName,singletonFactory)
创建Bean
创建Bean
synchronized(singletonObjects)
Object singletonObject=singletonObjects.get(beanName);
为空,一级缓存没有,进行创建
为空,一级缓存没有,进行创建
beforeSingletonCreation(beanName);
标记正在创建
标记正在创建
inCreationCheckExclusions.contains(beanName)
singletonsCurrentlyInCreation.add(beanName)
标记正在创建
标记正在创建
singletonObject=singletonFactory.getObject();
afterSingletonCreation(beanName);
inCreationCheckExclusions.contains(beanName)
singletonsCurrentlyInCreation.remove(beanName)
移除正在创建
移除正在创建
addSingleton(beanName,singletonObject);
synchronized(singletonObjects)
singletonObjects.put(beanName, singletonObject);
加入到一级缓存中(单例缓存池)
加入到一级缓存中(单例缓存池)
singletonFactories.remove(beanName);
从三级缓存中移除
从三级缓存中移除
earlySingletonObjects.remove(beanName);
从二级缓存中移除(循环依赖时 早期对象 存在于二级缓存)
从二级缓存中移除(循环依赖时 早期对象 存在于二级缓存)
registeredSingletons.add(beanName);
用来记录保存已经处理的bean
用来记录保存已经处理的bean
createBean(beanName,mbd,args);
RootBeanDefinition mbdToUse=mbd;
Class<?> resolvedClass=resolveBeanClass(mbd,beanName);
mbdToUse.prepareMethodOverrides();
XML中的 lookup-method 和 replace-method 场景
XML中的 lookup-method 和 replace-method 场景
Object bean=resolveBeforeInstantiation(beanName,mbdToUse);
if(bean!=null) return bean;
第一次调用BeanPostProcessor
可能有BeanPostProcessors创建代理对象
此步骤可阻止Spring容器创建对象,而使用自己实现的方法创建
if(bean!=null) return bean;
第一次调用BeanPostProcessor
可能有BeanPostProcessors创建代理对象
此步骤可阻止Spring容器创建对象,而使用自己实现的方法创建
bean=applyBeanPostProcessorsBeforeInstantiation(targetType,beanName);
getBeanPostProcessors()
bp instanceof InstantiationAwareBeanPostProcessor
ibp.postProcessBeforeInstantiation(beanClass,beanName);
bean=applyBeanPostProcessorsAfterInitialization(bean,beanName);
Object beanInstance=doCreateBean(beanName,mbdToUse,args);
mbd.isSingleton() -> factoryBeanInstanceCache.remove(beanName);
BeanWrapper instanceWrapper=createBeanInstance(beanName,mbd,args);
实例化bean(Supplier、反射实例化、工厂实例化(@Bean))
实例化bean(Supplier、反射实例化、工厂实例化(@Bean))
Class<?> beanClass=resolveBeanClass(mbd,beanName);
…………
Object bean=instanceWrapper.getWrappedInstance();
Class<?> beanType=instanceWrapper.getWrappedClass();
synchronized(mbd.postProcessingLock)
applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);
earlySingletonExposure=
mbd.isSingleton() &&
allowCircularReferences &&
singletonsCurrentlyInCreation.contains(beanName)
处理循环依赖
mbd.isSingleton() &&
allowCircularReferences &&
singletonsCurrentlyInCreation.contains(beanName)
处理循环依赖
addSingletonFactory(beanName,() -> getEarlyBeanReference(beanName,mbd,bean));
addSingletonFactory(beanName,singletonFactory)
synchronized(singletonObjects)
!singletonObjects.containsKey(beanName)
一级缓存没有
一级缓存没有
singletonFactories.put(beanName,singletonFactory)
放到三级缓存里
放到三级缓存里
earlySingletonObjects.remove(beanName);
从二级缓存移除
从二级缓存移除
registeredSingletons.add(beanName);
getEarlyBeanReference(beanName,mbd,bean)
!mbd.isSynthetic()&&hasInstantiationAwareBeanPostProcessors
getBeanPostProcessors()
bp instanceof SmartInstantiationAwareBeanPostProcessor
包括AbstractAutoProxyCreator,可使用AOP创建动态代理
包括AbstractAutoProxyCreator,可使用AOP创建动态代理
ibp.getEarlyBeanReference(exposedObject,beanName)
populateBean(beanName,mbd,instanceWrapper);
属性赋值
属性赋值
getBeanPostProcessors()
bp instanceof InstantiationAwareBeanPostProcessor
ibp.postProcessAfterInstantiation(bw.getWrappedInstance(),beanName)
mbd.getResolvedAutowireMode()
autowireByName(beanName,mbd,bw,newPvs);
autowireByType(beanName,mbd,bw,newPvs);
hasInstantiationAwareBeanPostProcessors
getBeanPostProcessors()
bp instanceof InstantiationAwareBeanPostProcessor
ibp.postProcessProperties(pvs,bw.getWrappedInstance(),beanName);
…………
exposedObject=initializeBean(beanName,exposedObject,mbd);
初始化
包括Aware、@PostConstruct、InitializingBean.afterPropertiesSet、initMethod
初始化
包括Aware、@PostConstruct、InitializingBean.afterPropertiesSet、initMethod
invokeAwareMethods(beanName,bean);
调用三个Aware
其他的在ApplicationContextAwareProcessor.invokeAwareInterfaces中调用
调用三个Aware
其他的在ApplicationContextAwareProcessor.invokeAwareInterfaces中调用
BeanNameAware.setBeanName(beanName);
BeanClassLoaderAware.setBeanClassLoader(getBeanClassLoader());
BeanFactoryAware.setBeanFactory(AbstractAutowireCapableBeanFactory.this);
applyBeanPostProcessorsBeforeInitialization(wrappedBean,beanName);
包括@PostConstruct(在CommonAnnotationBeanPostProcessor)
包括@PostConstruct(在CommonAnnotationBeanPostProcessor)
getBeanPostProcessors()
postProcessBeforeInitialization(result,beanName);
invokeInitMethods(beanName,wrappedBean,mbd);
applyBeanPostProcessorsAfterInitialization(wrappedBean,beanName);
AOP动态代理
AOP动态代理
getBeanPostProcessors()
postProcessAfterInitialization(result,beanName);
earlySingletonExposure
使用上边的变量
使用上边的变量
earlySingletonReference=getSingleton(beanName,false);
…………
registerDisposableBeanIfNecessary(beanName,bean,mbd);
bean=getObjectForBeanInstance(sharedInstance,name,beanName,mbd);
mbd.isPrototype()
beforePrototypeCreation(beanName);
prototypeInstance=createBean(beanName,mbd,args);
afterPrototypeCreation(beanName);
bean=getObjectForBeanInstance(prototypeInstance,name,beanName,mbd);
else
String scopeName=mbd.getScope();
Scope scope=this.scopes.get(scopeName);
String scopeName=mbd.getScope();
Scope scope=this.scopes.get(scopeName);
scopedInstance=scope.get(beanName,() -> {
beforePrototypeCreation(beanName);
createBean(beanName, mbd, args);
afterPrototypeCreation(beanName);
});
beforePrototypeCreation(beanName);
createBean(beanName, mbd, args);
afterPrototypeCreation(beanName);
});
bean=getObjectForBeanInstance(scopedInstance,name,beanName,mbd);
refresh();
prepareRefresh();
obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
finishRefresh();
resetCommonCaches();
BeanPostProcessors
InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(beanClass,beanName);
Aware
initializeBean(beanName,exposedObject,mbd);
->
invokeAwareMethods(beanName, bean);
->
invokeAwareMethods(beanName, bean);
BeanNameAware.setBeanName(beanName);
BeanClassLoaderAware.setBeanClassLoader(getBeanClassLoader());
BeanFactoryAware.setBeanFactory(AbstractAutowireCapableBeanFactory.this);
ApplicationContextAwareProcessor.postProcessBeforeInitialization(bean,beanName)
->
invokeAwareInterfaces(bean);
->
invokeAwareInterfaces(bean);
EnvironmentAware.setEnvironment(applicationContext.getEnvironment());
EmbeddedValueResolverAware.setEmbeddedValueResolver(embeddedValueResolver);
ResourceLoaderAware.setResourceLoader(applicationContext);
ApplicationEventPublisherAware.setApplicationEventPublisher(applicationContext);
MessageSourceAware.setMessageSource(applicationContext);
ApplicationContextAware.setApplicationContext(applicationContext);
0 条评论
下一页