// Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces like BeanFactoryAware. // 单例bean && 允许循环依赖 && bean正在被创建 boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } /** * 执行后置处理器SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference()方法尝试获取一个早期的引用。 * 并加入的单例工厂缓存中 * @see DefaultSingletonBeanRegistry#addSingletonFactory(String, ObjectFactory) * @see #getEarlyBeanReference */ addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }
// Initialize the bean instance. // 初始化bean实例,填充属性,注入依赖(@Autowired,@Resource,@Value)注解的属性 Object exposedObject = bean; try { populateBean(beanName, mbd, instanceWrapper); /** 执行bean的初始化回调方法以及执行后置处理器的初始化方法,包括: 一,执行Aware接口 ,包括BeanFactoryAware,BeanClassLoaderAware,BeanNameAware 注意:ApplicationContext的注入是在另外一个后置处理器ApplicationContextAwareProcessor中执行。 二,执行bean初始化回调,包括: 0. 执行初始化回调BeanPostProcessor.postProcessBeforeInitialization()方法 1. 执行初始化回调@PostConstruct注解定义的方法 2. 执行初始化回调InitializingBean.afterPropertiesSet()方法 3. 执行初始化回调@Bean(initMethod = "beanInit")定义的初始化方法beanInit() 4. 执行初始化回调BeanPostProcessor.postProcessAfterInitialization()方法 5. 执行初始化回调SmartInitializingSingleton.afterSingletonsInstantiated()方法 按照上述执行顺序执行 */ exposedObject = initializeBean(beanName, exposedObject, mbd); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { thrownew BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } // 循环依赖检查 if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } elseif (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (!actualDependentBeans.isEmpty()) { thrownew 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."); } } } }
/** * Initialize the given bean instance, applying factory callbacks * as well as init methods and bean post processors. * <p>Called from {@link #createBean} for traditionally defined beans, * and from {@link #initializeBean} for existing bean instances. * 本方法的作用有 * 一,执行Aware接口 ,包括BeanFactoryAware,BeanClassLoaderAware,BeanNameAware * 注意:ApplicationContext的注入是在另外一个后置处理器ApplicationContextAwareProcessor中执行。 * 二,执行bean初始化回调,包括: * 0. 执行初始化回调BeanPostProcessor.postProcessBeforeInitialization()方法 * 1. 执行初始化回调@PostConstruct注解定义的方法 * 2. 执行初始化回调InitializingBean.afterPropertiesSet()方法 * 3. 执行初始化回调@Bean(initMethod = "beanInit")定义的方法 * 4. 执行初始化回调BeanPostProcessor.postProcessAfterInitialization()方法 * 5. 执行初始化回调SmartInitializingSingleton.afterSingletonsInstantiated()方法 * 按照上述执行顺序执行 * * @param beanName the bean name in the factory (for debugging purposes) * @param bean the new bean instance we may need to initialize * @param mbd the bean definition that the bean was created with * (can also be {@code null}, if given an existing bean instance) * @return the initialized bean instance (potentially wrapped) * @see BeanNameAware * @see BeanClassLoaderAware * @see BeanFactoryAware * @see #applyBeanPostProcessorsBeforeInitialization * @see #invokeInitMethods * @see #applyBeanPostProcessorsAfterInitialization * 方法调用处: * @see #doCreateBean(String, RootBeanDefinition, Object[]) */ protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd){ // 如果bean实现了XxxAware接口,则调用这些接口的setXxx()方法 if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); returnnull; }, getAccessControlContext()); } else { invokeAwareMethods(beanName, bean); }