在Spring启动过程中,仅仅会把符合要求的业务Bean创建出来,并不是所有的Bean
1 并发创建Bean
1 2 3 4 5 6 7 8 9 10 11
| for (String beanName : beanNames) { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); if (!mbd.isAbstract() && mbd.isSingleton()) { CompletableFuture<?> future = preInstantiateSingleton(beanName, mbd); if (future != null) { futures.add(future); } } }
|
执行的链路是
1.1 preInstantiateSingleton
1 2 3 4 5 6 7 8 9 10
| if (!mbd.isLazyInit()) { try { instantiateSingleton(beanName); } catch (BeanCurrentlyInCreationException ex) { logger.info("Bean '" + beanName + "' marked for pre-instantiation (not lazy-init) " + "but currently initialized by other thread - skipping it in mainline thread"); } }
|
1.2 instantiateSingleton
1 2 3 4 5 6 7 8 9 10 11 12 13
| private void instantiateSingleton(String beanName) { if (isFactoryBean(beanName)) { Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof SmartFactoryBean<?> smartFactoryBean && smartFactoryBean.isEagerInit()) { getBean(beanName); } } else { getBean(beanName); } }
|
1.3 getBean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
@Override public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); }
|
1.4 取缓存的逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
protected @Nullable Object getSingleton(String beanName, boolean allowEarlyReference) { Object singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { if (!this.singletonLock.tryLock()) { return null; } try { singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null) { ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { singletonObject = singletonFactory.getObject(); if (this.singletonFactories.remove(beanName) != null) { this.earlySingletonObjects.put(beanName, singletonObject); } else { singletonObject = this.singletonObjects.get(beanName); } } } } } finally { this.singletonLock.unlock(); } } } return singletonObject; }
|
1.5 用BeanDefinition创建Bean
过程比较复杂,单独开一篇Spring-06-用BeanDefinition创建Bean
2 创建好后执行通知
执行SmartInitializingSingleton通知
1 2 3 4 5 6 7 8 9 10
| for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName, false); if (singletonInstance instanceof SmartInitializingSingleton smartSingleton) { StartupStep smartInitialize = getApplicationStartup().start("spring.beans.smart-initialize") .tag("beanName", beanName); smartSingleton.afterSingletonsInstantiated(); smartInitialize.end(); } }
|