欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring factory.getBean(name)过程

程序员文章站 2022-07-10 13:45:09
...
Eagerly check singleton cache for manually registered singletons
check if bean definition exists in this factory
Not fond ->check parent factory
Guarantee initialization of beans that the current bean depends on.//保证当前bean所依赖的bean必须初始化完成
getBean(dependsOnBean)
if the current bean is singleton ,create bean instance and register it
else if the merged bean is prototype, create new bean directly without registering
else create bean by another custom scope, out of box the web springframework  supports exactly five scopes.
etc. singleton,prototype,request,session,globalSession,application,and a CustomScopeProcessor Class of SimpleThreadScope
 
about "create bean"
give BeanPostProcessor a chance to return a proxy instead of the target bean instance
InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(beanClass, beanName)//比如:抑制目标对象的实例化,返回自己的一个对象。
Create a new instance using a appropriate instantiation strategy:factory method, autowire constructor, constructor, or simple instantiation. return BeanWrapper//作用是属性的访问,属性设置,属性类型转换。比如ResourceEditor可以将<property name="resource" value="/message.properties"/>转化为Resource resource。可以通过CustomEditorConfigurer将自己定制的转换器设置进去
Allow post-process to modify the merged bean definitions // MergedBeanDefinitionPostProcessor  收集bean类型里的Annotation,将其缓存在该processor中,在后面会用它来执行注入
Eagerly cache singletons to be able to resolve circular references // singletonsCurrentlyInCreation.add(A)  A->B   B->A  
populate the bean Instance in the given BeanWrapper with the property values  //填充属性值到bean实例。分别执行:InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation 和 InstantiationAwareBeanPostProcessor.postProcessPropertyValues (比如:将@Autoware,@Required,@Resource属性设置进实例)
initialize the bean instance : invoke aware method(往bean注入beanName, classLoader, beanFactory),BeanPostProcessor.postProcessorBeforeInitialization (最主要的一个例子就是ApplicationContextAwareProcessor,它提供了ResourceLoader,EventPublisher,ApplicationContext等)
invoke afterPropertiesSet and init method
BeanPostProcessor.postProcessorAfterInitialization(BeanNameAutoProxyCreator根据BeanNames判断是否代理)