Spring Bean的创建过程流程图
2023-02-01 16:30:48 4 举报
Spring Bean的创建生命周期
作者其他创作
大纲/内容
true
dependsOn数组是否遍历完成
如果当前作用域是Session,这Scope为SessionScope
font color=\"#323232\
final FactoryBean<?> factory = (FactoryBean<?>) bean;
抽象指的时抽象的beanDefinition,不是生成bean的那个类是抽象的,类已经在扫描时过滤了
只有单例的非懒加载的以及beanDefinition不是抽象的beanDefinition才进行bean的创建if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit())
SpringAOP和Spring事务的实现后置处理器processor.postProcessAfterInitialization
提交调用FactoryBean的getObject()getBean(beanName);
获取父容器,当前单例池中获取不到,在从父容器单例池中获取,springMVC会用到,这里Spring并没有设置父容器,为nullBeanFactory parentBeanFactory = getParentBeanFactory();
throw new BeanCreationException
初始化后applyBeanPostProcessorsAfterInitialization
找到Bean的真正名称final String beanName = transformedBeanName(name);
所有单例非懒加载的bean创建完成后再次遍历所有创建好的bean,是否继承SmartInitializingSingleton接口如果实现了调用接口的afterSingletonsInstantiated方法Spring的一个扩展点,如@LoadBalance注解的实现smartSingleton.afterSingletonsInstantiated();
false
遍历beanNames
其他作用域的bean例如:request、session等作用域
for (String dep : dependsOn)
bean创建getBean(beanName);
初始化前:@PostConstruct注解方法调用实现Aware接口回调:EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAwareBeanPostProcessor.postProcessBeforeInitialization()
调用继承InitializingBean接口的afterPropertiesSet方法((InitializingBean) bean).afterPropertiesSet();
singletonObject = singletonFactory.getObject();
拿到@DependOn注解上的值String[] dependsOn = mbd.getDependsOn();
preInstantiateSingletons()
优先创建依赖beangetBean(dep);
合并BeanDefinition,生成真正用来创建bean的定义RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
是否是原型beanmbd.isPrototype()
合并beanDefinitionfinal RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
true遍历dependsOn数组
实例化后bean后置处理器InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass);
获取扫描出的所有需要创建的bean的beanNamesList<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
web环境下,会向this.scopes注册作用域,这里没有web环境返回为nullfinal Scope scope = this.scopes.get(scopeName);
getSingleton(beanName,singletonFactory)
假设不为null
getBean(beanName);
判断当前需要建立的bean是否是FactoryBeanif (isFactoryBean(beanName))
是否是单例beanif (mbd.isSingleton())
beanNames是否遍历完成
在单例池中创建一个&+beanName为key的Bean对象Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
先从单例池中获取bean,第一次创建肯定是没有的Object sharedInstance = getSingleton(beanName);
初始化invokeInitMethods
for (String beanName : beanNames)
处理合并的beanDefinition后置处理器MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition
如果当前继承的时SmartFactoryBean ,并且其中isEagerInit方法返回true,提前调用FactoryBean的getObject()factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()
if (dependsOn != null)
属性赋值,处理@Autowire、@Bean、@Value注解进行属性赋值InstantiationAwareBeanPostProcessor.postProcessProperties()
0 条评论
下一页