Bean的创建过程

Bean的创建实际上是由AbstractAutowireCapableBeanFactory的createBean方法内部实现的,

  1. protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
  2. throws BeanCreationException {
  3. AccessControlContext acc = AccessController.getContext();
  4. return AccessController.doPrivileged(new PrivilegedAction() {
  5. public Object run() {
  6. if (logger.isDebugEnabled()) {
  7. logger.debug("Creating instance of bean '" + beanName + "'");
  8. }
  9. // Make sure bean class is actually resolved at this point.
  10. resolveBeanClass(mbd, beanName);
  11. // Prepare method overrides.
  12. try {
  13. mbd.prepareMethodOverrides();
  14. }
  15. catch (BeanDefinitionValidationException ex) {
  16. throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
  17. beanName, "Validation of method overrides failed", ex);
  18. }
  19. try {
  20. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  21. Object bean = resolveBeforeInstantiation(beanName, mbd);
  22. if (bean != null) {
  23. return bean;
  24. }
  25. }
  26. catch (Throwable ex) {
  27. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  28. "BeanPostProcessor before instantiation of bean failed", ex);
  29. }
  30. Object beanInstance = doCreateBean(beanName, mbd, args);
  31. if (logger.isDebugEnabled()) {
  32. logger.debug("Finished creating instance of bean '" + beanName + "'");
  33. }
  34. return beanInstance;
  35. }
  36. }, acc);
  37. }

内部真正干活的是doCreateBean,里面包含了对于单例模式循环引用的处理,bean属性的设置和初始化的工作

  1. rotected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
  2. // Instantiate the bean.
  3. BeanWrapper instanceWrapper = null;
  4. if (mbd.isSingleton()) {
  5. instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName);
  6. }
  7. if (instanceWrapper == null) {
  8. instanceWrapper = createBeanInstance(beanName, mbd, args);
  9. }
  10. final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
  11. Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
  12. // Allow post-processors to modify the merged bean definition.
  13. synchronized (mbd.postProcessingLock) {
  14. if (!mbd.postProcessed) {
  15. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  16. mbd.postProcessed = true;
  17. }
  18. }
  19. // Eagerly cache singletons to be able to resolve circular references
  20. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  21. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  22. isSingletonCurrentlyInCreation(beanName));
  23. if (earlySingletonExposure) {
  24. if (logger.isDebugEnabled()) {
  25. logger.debug("Eagerly caching bean '" + beanName +
  26. "' to allow for resolving potential circular references");
  27. }
  28. addSingletonFactory(beanName, new ObjectFactory() {
  29. public Object getObject() throws BeansException {
  30. return getEarlyBeanReference(beanName, mbd, bean);
  31. }
  32. });
  33. }
  34. // Initialize the bean instance.
  35. Object exposedObject = bean;
  36. try {
  37. populateBean(beanName, mbd, instanceWrapper);
  38. exposedObject = initializeBean(beanName, exposedObject, mbd);
  39. }
  40. catch (Throwable ex) {
  41. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  42. throw (BeanCreationException) ex;
  43. }
  44. else {
  45. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  46. }
  47. }
  48. if (earlySingletonExposure) {
  49. Object earlySingletonReference = getSingleton(beanName, false);
  50. if (earlySingletonReference != null) {
  51. if (exposedObject == bean) {
  52. exposedObject = earlySingletonReference;
  53. }
  54. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  55. String[] dependentBeans = getDependentBeans(beanName);
  56. Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
  57. for (int i = 0; i < dependentBeans.length; i++) {
  58. String dependentBean = dependentBeans[i];
  59. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  60. actualDependentBeans.add(dependentBean);
  61. }
  62. }
  63. if (!actualDependentBeans.isEmpty()) {
  64. throw new BeanCurrentlyInCreationException(beanName,
  65. "Bean with name '" + beanName + "' has been injected into other beans [" +
  66. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  67. "] in its raw version as part of a circular reference, but has eventually been " +
  68. "wrapped. This means that said other beans do not use the final version of the " +
  69. "bean. This is often the result of over-eager type matching - consider using " +
  70. "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
  71. }
  72. }
  73. }
  74. }
  75. // Register bean as disposable.
  76. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  77. return exposedObject;
  78. }

得到Bean的实例之后,接下来进行初始化Bean
(1)设置Bean的属性
(2)initializeBean,里面首先是各种Aware,然后是applyBeanPostProcessorsBeforeInitialization,然后是调用初始化方法,然后是applyBeanPostProcessorsAfterInitialization

  1. protected Object initializeBean(String beanName, Object bean, RootBeanDefinition mbd) {
  2. if (bean instanceof BeanNameAware) {
  3. ((BeanNameAware) bean).setBeanName(beanName);
  4. }
  5. if (bean instanceof BeanClassLoaderAware) {
  6. ((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
  7. }
  8. if (bean instanceof BeanFactoryAware) {
  9. ((BeanFactoryAware) bean).setBeanFactory(this);
  10. }
  11. Object wrappedBean = bean;
  12. if (mbd == null || !mbd.isSynthetic()) {
  13. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  14. }
  15. try {
  16. invokeInitMethods(beanName, wrappedBean, mbd);
  17. }
  18. catch (Throwable ex) {
  19. throw new BeanCreationException(
  20. (mbd != null ? mbd.getResourceDescription() : null),
  21. beanName, "Invocation of init method failed", ex);
  22. }
  23. if (mbd == null || !mbd.isSynthetic()) {
  24. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  25. }
  26. return wrappedBean;
  27. }