一、Bean的生命周期

1.1 相对完整的生命周期

Spring V2 - 图1

1.2.1 结合代码分析

1. 从容器创建入手

  1. public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
  2. this(configLocations, true, null);
  3. }
  1. public ClassPathXmlApplicationContext(
  2. String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
  3. throws BeansException {
  4. super(parent);
  5. setConfigLocations(configLocations);
  6. if (refresh) {
  7. refresh();
  8. }
  9. }

发现其中一个核心的方法refresh()

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized (this.startupShutdownMonitor) {
  4. StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
  5. // Prepare this context for refreshing.
  6. prepareRefresh();
  7. // Tell the subclass to refresh the internal bean factory.
  8. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  9. // Prepare the bean factory for use in this context.
  10. prepareBeanFactory(beanFactory);
  11. try {
  12. // Allows post-processing of the bean factory in context subclasses.
  13. postProcessBeanFactory(beanFactory);
  14. StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
  15. // Invoke factory processors registered as beans in the context.
  16. invokeBeanFactoryPostProcessors(beanFactory);
  17. // Register bean processors that intercept bean creation.
  18. registerBeanPostProcessors(beanFactory);
  19. beanPostProcess.end();
  20. // Initialize message source for this context.
  21. initMessageSource();
  22. // Initialize event multicaster for this context.
  23. initApplicationEventMulticaster();
  24. // Initialize other special beans in specific context subclasses.
  25. onRefresh();
  26. // Check for listener beans and register them.
  27. registerListeners();
  28. // Instantiate all remaining (non-lazy-init) singletons.
  29. finishBeanFactoryInitialization(beanFactory);
  30. // Last step: publish corresponding event.
  31. finishRefresh();
  32. }
  33. catch (BeansException ex) {
  34. if (logger.isWarnEnabled()) {
  35. logger.warn("Exception encountered during context initialization - " +
  36. "cancelling refresh attempt: " + ex);
  37. }
  38. // Destroy already created singletons to avoid dangling resources.
  39. destroyBeans();
  40. // Reset 'active' flag.
  41. cancelRefresh(ex);
  42. // Propagate exception to caller.
  43. throw ex;
  44. }
  45. finally {
  46. // Reset common introspection caches in Spring's core, since we
  47. // might not ever need metadata for singleton beans anymore...
  48. resetCommonCaches();
  49. contextRefresh.end();
  50. }
  51. }
  52. }

2. prepareRefresh()

此方法内部是刷新前的预期准备工作,包括启动时间的配置、容器状态的变更、属性资源的初始化、环境的验证以及一些集合的初始化工作。

  1. protected void prepareRefresh() {
  2. // Switch to active.
  3. this.startupDate = System.currentTimeMillis();
  4. this.closed.set(false);
  5. this.active.set(true);
  6. if (logger.isDebugEnabled()) {
  7. if (logger.isTraceEnabled()) {
  8. logger.trace("Refreshing " + this);
  9. }
  10. else {
  11. logger.debug("Refreshing " + getDisplayName());
  12. }
  13. }
  14. // Initialize any placeholder property sources in the context environment.
  15. initPropertySources();
  16. // Validate that all properties marked as required are resolvable:
  17. // see ConfigurablePropertyResolver#setRequiredProperties
  18. getEnvironment().validateRequiredProperties();
  19. // Store pre-refresh ApplicationListeners...
  20. if (this.earlyApplicationListeners == null) {
  21. this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
  22. }
  23. else {
  24. // Reset local application listeners to pre-refresh state.
  25. this.applicationListeners.clear();
  26. this.applicationListeners.addAll(this.earlyApplicationListeners);
  27. }
  28. // Allow for the collection of early ApplicationEvents,
  29. // to be published once the multicaster is available...
  30. this.earlyApplicationEvents = new LinkedHashSet<>();
  31. }

3. obtainFreshBeanFactory()

此方法主要是用来创建BeanFactory,并将Bean定义信息加载到BeanFactory中。

  1. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  2. refreshBeanFactory();
  3. return getBeanFactory();
  4. }
  1. @Override
  2. protected final void refreshBeanFactory() throws BeansException {
  3. if (hasBeanFactory()) { // 如果已经有BeanFactory,则销毁bean,关闭BeanFactory
  4. destroyBeans();
  5. closeBeanFactory();
  6. }
  7. try {
  8. // 创建BeanFactory
  9. DefaultListableBeanFactory beanFactory = createBeanFactory();
  10. beanFactory.setSerializationId(getId());
  11. // 自定义BeanFactory
  12. customizeBeanFactory(beanFactory);
  13. // 加载BeanDefinition到BeanFactory
  14. loadBeanDefinitions(beanFactory);
  15. this.beanFactory = beanFactory;
  16. }
  17. catch (IOException ex) {
  18. throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  19. }
  20. }

4. prepareBeanFactory(beanFactory)

此一步骤,主要是为了给上步骤创建好的BeanFactory设置一些属性信息,完善其配置。

  1. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  2. // Tell the internal bean factory to use the context's class loader etc.
  3. beanFactory.setBeanClassLoader(getClassLoader());
  4. if (!shouldIgnoreSpel) {
  5. beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
  6. }
  7. beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
  8. // Configure the bean factory with context callbacks.
  9. beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
  10. beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
  11. beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
  12. beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
  13. beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
  14. beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
  15. beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
  16. beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);
  17. // BeanFactory interface not registered as resolvable type in a plain factory.
  18. // MessageSource registered (and found for autowiring) as a bean.
  19. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
  20. beanFactory.registerResolvableDependency(ResourceLoader.class, this);
  21. beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
  22. beanFactory.registerResolvableDependency(ApplicationContext.class, this);
  23. // Register early post-processor for detecting inner beans as ApplicationListeners.
  24. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
  25. // Detect a LoadTimeWeaver and prepare for weaving, if found.
  26. if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
  27. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
  28. // Set a temporary ClassLoader for type matching.
  29. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  30. }
  31. // Register default environment beans.
  32. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
  33. beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
  34. }
  35. if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
  36. beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
  37. }
  38. if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
  39. beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
  40. }
  41. if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
  42. beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
  43. }
  44. }

5. postProcessBeanFactory(beanFactory)

此一步骤,是为了支持去注册一些特殊的BeanFactoryPostProcessor,为BeanFactory做增强操作。可以看到,此方法内部实现为空,是留给子类对扩展实现的。

  1. protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  2. }

6. invokeBeanFactoryPostProcessors(beanFactory)

执行此步骤,是实例化并执行所有已经注册的BeanFactoryPostProcessor,实现对BeanFactory做增强操作。

  1. protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  2. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
  3. // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
  4. // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
  5. if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
  6. beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
  7. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  8. }
  9. }

7. registerBeanPostProcessors(beanFactory)

注册BeanPostProcessor。

  1. protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
  2. PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
  3. }

8. initMessageSource()

初始化消息源,常用于国际化等。

  1. protected void initMessageSource() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
  4. this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
  5. // Make MessageSource aware of parent MessageSource.
  6. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
  7. HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
  8. if (hms.getParentMessageSource() == null) {
  9. // Only set parent context as parent MessageSource if no parent MessageSource
  10. // registered already.
  11. hms.setParentMessageSource(getInternalParentMessageSource());
  12. }
  13. }
  14. if (logger.isTraceEnabled()) {
  15. logger.trace("Using MessageSource [" + this.messageSource + "]");
  16. }
  17. }
  18. else {
  19. // Use empty MessageSource to be able to accept getMessage calls.
  20. DelegatingMessageSource dms = new DelegatingMessageSource();
  21. dms.setParentMessageSource(getInternalParentMessageSource());
  22. this.messageSource = dms;
  23. beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
  24. if (logger.isTraceEnabled()) {
  25. logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
  26. }
  27. }
  28. }

9. initApplicationEventMulticaster()

初始化应用程序中的事件多播器

  1. protected void initApplicationEventMulticaster() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
  4. this.applicationEventMulticaster =
  5. beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
  6. if (logger.isTraceEnabled()) {
  7. logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
  8. }
  9. }
  10. else {
  11. this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
  12. beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
  13. if (logger.isTraceEnabled()) {
  14. logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
  15. "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
  16. }
  17. }
  18. }

10. onRefresh()

初始化一些特殊子容器中的特殊bean,内部为空实现,由子类实现。

  1. protected void onRefresh() throws BeansException {
  2. // For subclasses: do nothing by default.
  3. }

11. registerListeners()

注册监听器。

  1. protected void registerListeners() {
  2. // Register statically specified listeners first.
  3. for (ApplicationListener<?> listener : getApplicationListeners()) {
  4. getApplicationEventMulticaster().addApplicationListener(listener);
  5. }
  6. // Do not initialize FactoryBeans here: We need to leave all regular beans
  7. // uninitialized to let post-processors apply to them!
  8. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  9. for (String listenerBeanName : listenerBeanNames) {
  10. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  11. }
  12. // Publish early application events now that we finally have a multicaster...
  13. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  14. this.earlyApplicationEvents = null;
  15. if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
  16. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  17. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  18. }
  19. }
  20. }

12. finishBeanFactoryInitialization(beanFactory)

a. Bean的实例化

实例化所有剩下的非懒加载的Bean。

  1. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  2. // Initialize conversion service for this context.
  3. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  4. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  5. beanFactory.setConversionService(
  6. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  7. }
  8. // Register a default embedded value resolver if no BeanFactoryPostProcessor
  9. // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
  10. // at this point, primarily for resolution in annotation attribute values.
  11. if (!beanFactory.hasEmbeddedValueResolver()) {
  12. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
  13. }
  14. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  15. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  16. for (String weaverAwareName : weaverAwareNames) {
  17. getBean(weaverAwareName);
  18. }
  19. // Stop using the temporary ClassLoader for type matching.
  20. beanFactory.setTempClassLoader(null);
  21. // Allow for caching all bean definition metadata, not expecting further changes.
  22. beanFactory.freezeConfiguration();
  23. // Instantiate all remaining (non-lazy-init) singletons.
  24. // 此处是重点,预实例化单例Bean
  25. beanFactory.preInstantiateSingletons();
  26. }
  1. @Override
  2. public void preInstantiateSingletons() throws BeansException {
  3. if (logger.isTraceEnabled()) {
  4. logger.trace("Pre-instantiating singletons in " + this);
  5. }
  6. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  7. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  8. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
  9. // Trigger initialization of all non-lazy singleton beans...
  10. for (String beanName : beanNames) {
  11. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  12. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  13. if (isFactoryBean(beanName)) {
  14. Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
  15. if (bean instanceof FactoryBean) {
  16. FactoryBean<?> factory = (FactoryBean<?>) bean;
  17. boolean isEagerInit;
  18. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  19. isEagerInit = AccessController.doPrivileged(
  20. (PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
  21. getAccessControlContext());
  22. }
  23. else {
  24. isEagerInit = (factory instanceof SmartFactoryBean &&
  25. ((SmartFactoryBean<?>) factory).isEagerInit());
  26. }
  27. if (isEagerInit) {
  28. getBean(beanName);
  29. }
  30. }
  31. }
  32. else {
  33. // 此处是重点,获取Bean
  34. getBean(beanName);
  35. }
  36. }
  37. }
  1. @Override
  2. public Object getBean(String name) throws BeansException {
  3. return doGetBean(name, null, null, false);
  4. }
  1. protected <T> T doGetBean(
  2. String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
  3. throws BeansException {
  4. String beanName = transformedBeanName(name);
  5. Object beanInstance;
  6. // Eagerly check singleton cache for manually registered singletons.
  7. Object sharedInstance = getSingleton(beanName);
  8. if (sharedInstance != null && args == null) {
  9. if (logger.isTraceEnabled()) {
  10. if (isSingletonCurrentlyInCreation(beanName)) {
  11. logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
  12. "' that is not fully initialized yet - a consequence of a circular reference");
  13. }
  14. else {
  15. logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
  16. }
  17. }
  18. beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  19. }
  20. else {
  21. // Fail if we're already creating this bean instance:
  22. // We're assumably within a circular reference.
  23. if (isPrototypeCurrentlyInCreation(beanName)) {
  24. throw new BeanCurrentlyInCreationException(beanName);
  25. }
  26. // Check if bean definition exists in this factory.
  27. BeanFactory parentBeanFactory = getParentBeanFactory();
  28. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  29. // Not found -> check parent.
  30. String nameToLookup = originalBeanName(name);
  31. if (parentBeanFactory instanceof AbstractBeanFactory) {
  32. return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
  33. nameToLookup, requiredType, args, typeCheckOnly);
  34. }
  35. else if (args != null) {
  36. // Delegation to parent with explicit args.
  37. return (T) parentBeanFactory.getBean(nameToLookup, args);
  38. }
  39. else if (requiredType != null) {
  40. // No args -> delegate to standard getBean method.
  41. return parentBeanFactory.getBean(nameToLookup, requiredType);
  42. }
  43. else {
  44. return (T) parentBeanFactory.getBean(nameToLookup);
  45. }
  46. }
  47. if (!typeCheckOnly) {
  48. markBeanAsCreated(beanName);
  49. }
  50. StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
  51. .tag("beanName", name);
  52. try {
  53. if (requiredType != null) {
  54. beanCreation.tag("beanType", requiredType::toString);
  55. }
  56. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  57. checkMergedBeanDefinition(mbd, beanName, args);
  58. // Guarantee initialization of beans that the current bean depends on.
  59. String[] dependsOn = mbd.getDependsOn();
  60. if (dependsOn != null) {
  61. for (String dep : dependsOn) {
  62. if (isDependent(beanName, dep)) {
  63. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  64. "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
  65. }
  66. registerDependentBean(dep, beanName);
  67. try {
  68. getBean(dep);
  69. }
  70. catch (NoSuchBeanDefinitionException ex) {
  71. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  72. "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
  73. }
  74. }
  75. }
  76. // Create bean instance.
  77. if (mbd.isSingleton()) {
  78. sharedInstance = getSingleton(beanName, () -> {
  79. try {
  80. // 此处是重点,创建bean
  81. return createBean(beanName, mbd, args);
  82. }
  83. catch (BeansException ex) {
  84. // Explicitly remove instance from singleton cache: It might have been put there
  85. // eagerly by the creation process, to allow for circular reference resolution.
  86. // Also remove any beans that received a temporary reference to the bean.
  87. destroySingleton(beanName);
  88. throw ex;
  89. }
  90. });
  91. beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  92. }
  93. else if (mbd.isPrototype()) {
  94. // It's a prototype -> create a new instance.
  95. Object prototypeInstance = null;
  96. try {
  97. beforePrototypeCreation(beanName);
  98. prototypeInstance = createBean(beanName, mbd, args);
  99. }
  100. finally {
  101. afterPrototypeCreation(beanName);
  102. }
  103. beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  104. }
  105. else {
  106. String scopeName = mbd.getScope();
  107. if (!StringUtils.hasLength(scopeName)) {
  108. throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
  109. }
  110. Scope scope = this.scopes.get(scopeName);
  111. if (scope == null) {
  112. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  113. }
  114. try {
  115. Object scopedInstance = scope.get(beanName, () -> {
  116. beforePrototypeCreation(beanName);
  117. try {
  118. return createBean(beanName, mbd, args);
  119. }
  120. finally {
  121. afterPrototypeCreation(beanName);
  122. }
  123. });
  124. beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  125. }
  126. catch (IllegalStateException ex) {
  127. throw new ScopeNotActiveException(beanName, scopeName, ex);
  128. }
  129. }
  130. }
  131. catch (BeansException ex) {
  132. beanCreation.tag("exception", ex.getClass().toString());
  133. beanCreation.tag("message", String.valueOf(ex.getMessage()));
  134. cleanupAfterBeanCreationFailure(beanName);
  135. throw ex;
  136. }
  137. finally {
  138. beanCreation.end();
  139. }
  140. }
  141. return adaptBeanInstance(name, beanInstance, requiredType);
  142. }
  1. @Override
  2. protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  3. throws BeanCreationException {
  4. if (logger.isTraceEnabled()) {
  5. logger.trace("Creating instance of bean '" + beanName + "'");
  6. }
  7. RootBeanDefinition mbdToUse = mbd;
  8. // Make sure bean class is actually resolved at this point, and
  9. // clone the bean definition in case of a dynamically resolved Class
  10. // which cannot be stored in the shared merged bean definition.
  11. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  12. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  13. mbdToUse = new RootBeanDefinition(mbd);
  14. mbdToUse.setBeanClass(resolvedClass);
  15. }
  16. // Prepare method overrides.
  17. try {
  18. mbdToUse.prepareMethodOverrides();
  19. }
  20. catch (BeanDefinitionValidationException ex) {
  21. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  22. beanName, "Validation of method overrides failed", ex);
  23. }
  24. try {
  25. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  26. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  27. if (bean != null) {
  28. return bean;
  29. }
  30. }
  31. catch (Throwable ex) {
  32. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  33. "BeanPostProcessor before instantiation of bean failed", ex);
  34. }
  35. try {
  36. // 此处是重点,创建Bean
  37. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  38. if (logger.isTraceEnabled()) {
  39. logger.trace("Finished creating instance of bean '" + beanName + "'");
  40. }
  41. return beanInstance;
  42. }
  43. catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
  44. // A previously detected exception with proper bean creation context already,
  45. // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
  46. throw ex;
  47. }
  48. catch (Throwable ex) {
  49. throw new BeanCreationException(
  50. mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
  51. }
  52. }
  1. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. // Instantiate the bean.
  4. BeanWrapper instanceWrapper = null;
  5. if (mbd.isSingleton()) {
  6. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  7. }
  8. if (instanceWrapper == null) {
  9. // 此处是重点,创建Bean实例
  10. instanceWrapper = createBeanInstance(beanName, mbd, args);
  11. }
  12. Object bean = instanceWrapper.getWrappedInstance();
  13. Class<?> beanType = instanceWrapper.getWrappedClass();
  14. if (beanType != NullBean.class) {
  15. mbd.resolvedTargetType = beanType;
  16. }
  17. // Allow post-processors to modify the merged bean definition.
  18. synchronized (mbd.postProcessingLock) {
  19. if (!mbd.postProcessed) {
  20. try {
  21. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  22. }
  23. catch (Throwable ex) {
  24. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  25. "Post-processing of merged bean definition failed", ex);
  26. }
  27. mbd.postProcessed = true;
  28. }
  29. }
  30. // Eagerly cache singletons to be able to resolve circular references
  31. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  32. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  33. isSingletonCurrentlyInCreation(beanName));
  34. if (earlySingletonExposure) {
  35. if (logger.isTraceEnabled()) {
  36. logger.trace("Eagerly caching bean '" + beanName +
  37. "' to allow for resolving potential circular references");
  38. }
  39. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  40. }
  41. // Initialize the bean instance.
  42. Object exposedObject = bean;
  43. try {
  44. populateBean(beanName, mbd, instanceWrapper);
  45. exposedObject = initializeBean(beanName, exposedObject, mbd);
  46. }
  47. catch (Throwable ex) {
  48. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  49. throw (BeanCreationException) ex;
  50. }
  51. else {
  52. throw new BeanCreationException(
  53. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  54. }
  55. }
  56. if (earlySingletonExposure) {
  57. Object earlySingletonReference = getSingleton(beanName, false);
  58. if (earlySingletonReference != null) {
  59. if (exposedObject == bean) {
  60. exposedObject = earlySingletonReference;
  61. }
  62. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  63. String[] dependentBeans = getDependentBeans(beanName);
  64. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  65. for (String dependentBean : dependentBeans) {
  66. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  67. actualDependentBeans.add(dependentBean);
  68. }
  69. }
  70. if (!actualDependentBeans.isEmpty()) {
  71. throw new BeanCurrentlyInCreationException(beanName,
  72. "Bean with name '" + beanName + "' has been injected into other beans [" +
  73. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  74. "] in its raw version as part of a circular reference, but has eventually been " +
  75. "wrapped. This means that said other beans do not use the final version of the " +
  76. "bean. This is often the result of over-eager type matching - consider using " +
  77. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  78. }
  79. }
  80. }
  81. }
  82. // Register bean as disposable.
  83. try {
  84. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  85. }
  86. catch (BeanDefinitionValidationException ex) {
  87. throw new BeanCreationException(
  88. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  89. }
  90. return exposedObject;
  91. }
  1. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
  2. // Make sure bean class is actually resolved at this point.
  3. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  4. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
  5. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  6. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  7. }
  8. Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
  9. if (instanceSupplier != null) {
  10. return obtainFromSupplier(instanceSupplier, beanName);
  11. }
  12. if (mbd.getFactoryMethodName() != null) {
  13. return instantiateUsingFactoryMethod(beanName, mbd, args);
  14. }
  15. // Shortcut when re-creating the same bean...
  16. boolean resolved = false;
  17. boolean autowireNecessary = false;
  18. if (args == null) {
  19. synchronized (mbd.constructorArgumentLock) {
  20. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  21. resolved = true;
  22. autowireNecessary = mbd.constructorArgumentsResolved;
  23. }
  24. }
  25. }
  26. if (resolved) {
  27. if (autowireNecessary) {
  28. return autowireConstructor(beanName, mbd, null, null);
  29. }
  30. else {
  31. return instantiateBean(beanName, mbd);
  32. }
  33. }
  34. // Candidate constructors for autowiring?
  35. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  36. if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
  37. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  38. return autowireConstructor(beanName, mbd, ctors, args);
  39. }
  40. // Preferred constructors for default construction?
  41. ctors = mbd.getPreferredConstructors();
  42. if (ctors != null) {
  43. return autowireConstructor(beanName, mbd, ctors, null);
  44. }
  45. // No special handling: simply use no-arg constructor.
  46. // 此处是重点,如果没有特殊处理,就使用无参构造创建Bean对象
  47. return instantiateBean(beanName, mbd);
  48. }
  1. protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
  2. try {
  3. Object beanInstance;
  4. if (System.getSecurityManager() != null) {
  5. beanInstance = AccessController.doPrivileged(
  6. (PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
  7. getAccessControlContext());
  8. }
  9. else {
  10. // 此处是重点,调用实例化策略,进行实例化
  11. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
  12. }
  13. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  14. initBeanWrapper(bw);
  15. return bw;
  16. }
  17. catch (Throwable ex) {
  18. throw new BeanCreationException(
  19. mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  20. }
  21. }
  1. @Override
  2. public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
  3. // Don't override the class with CGLIB if no overrides.
  4. if (!bd.hasMethodOverrides()) {
  5. Constructor<?> constructorToUse;
  6. synchronized (bd.constructorArgumentLock) {
  7. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  8. if (constructorToUse == null) {
  9. final Class<?> clazz = bd.getBeanClass();
  10. if (clazz.isInterface()) {
  11. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  12. }
  13. try {
  14. if (System.getSecurityManager() != null) {
  15. constructorToUse = AccessController.doPrivileged(
  16. (PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
  17. }
  18. else {
  19. // 通过反射,获取构造方法
  20. constructorToUse = clazz.getDeclaredConstructor();
  21. }
  22. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  23. }
  24. catch (Throwable ex) {
  25. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  26. }
  27. }
  28. }
  29. // 通过Bean工具来调用构造方法进行实例化
  30. return BeanUtils.instantiateClass(constructorToUse);
  31. }
  32. else {
  33. // Must generate CGLIB subclass.
  34. return instantiateWithMethodInjection(bd, beanName, owner);
  35. }
  36. }
  1. public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
  2. Assert.notNull(ctor, "Constructor must not be null");
  3. try {
  4. ReflectionUtils.makeAccessible(ctor);
  5. if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
  6. return KotlinDelegate.instantiateClass(ctor, args);
  7. }
  8. else {
  9. Class<?>[] parameterTypes = ctor.getParameterTypes();
  10. Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
  11. Object[] argsWithDefaultValues = new Object[args.length];
  12. for (int i = 0 ; i < args.length; i++) {
  13. if (args[i] == null) {
  14. Class<?> parameterType = parameterTypes[i];
  15. argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
  16. }
  17. else {
  18. argsWithDefaultValues[i] = args[i];
  19. }
  20. }
  21. // 此处使用构造方法创建实例
  22. return ctor.newInstance(argsWithDefaultValues);
  23. }
  24. }
  25. catch (InstantiationException ex) {
  26. throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
  27. }
  28. catch (IllegalAccessException ex) {
  29. throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
  30. }
  31. catch (IllegalArgumentException ex) {
  32. throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
  33. }
  34. catch (InvocationTargetException ex) {
  35. throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
  36. }
  37. }

b. Bean的属性赋值及初始化
  1. protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
  2. throws BeanCreationException {
  3. // Instantiate the bean.
  4. BeanWrapper instanceWrapper = null;
  5. if (mbd.isSingleton()) {
  6. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  7. }
  8. if (instanceWrapper == null) {
  9. instanceWrapper = createBeanInstance(beanName, mbd, args);
  10. }
  11. Object bean = instanceWrapper.getWrappedInstance();
  12. Class<?> beanType = instanceWrapper.getWrappedClass();
  13. if (beanType != NullBean.class) {
  14. mbd.resolvedTargetType = beanType;
  15. }
  16. // Allow post-processors to modify the merged bean definition.
  17. synchronized (mbd.postProcessingLock) {
  18. if (!mbd.postProcessed) {
  19. try {
  20. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  21. }
  22. catch (Throwable ex) {
  23. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  24. "Post-processing of merged bean definition failed", ex);
  25. }
  26. mbd.postProcessed = true;
  27. }
  28. }
  29. // Eagerly cache singletons to be able to resolve circular references
  30. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  31. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  32. isSingletonCurrentlyInCreation(beanName));
  33. if (earlySingletonExposure) {
  34. if (logger.isTraceEnabled()) {
  35. logger.trace("Eagerly caching bean '" + beanName +
  36. "' to allow for resolving potential circular references");
  37. }
  38. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
  39. }
  40. // Initialize the bean instance.
  41. Object exposedObject = bean;
  42. try {
  43. // 填充Bean的属性值
  44. populateBean(beanName, mbd, instanceWrapper);
  45. // Bean的初始化
  46. exposedObject = initializeBean(beanName, exposedObject, mbd);
  47. }
  48. catch (Throwable ex) {
  49. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  50. throw (BeanCreationException) ex;
  51. }
  52. else {
  53. throw new BeanCreationException(
  54. mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  55. }
  56. }
  57. if (earlySingletonExposure) {
  58. Object earlySingletonReference = getSingleton(beanName, false);
  59. if (earlySingletonReference != null) {
  60. if (exposedObject == bean) {
  61. exposedObject = earlySingletonReference;
  62. }
  63. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  64. String[] dependentBeans = getDependentBeans(beanName);
  65. Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
  66. for (String dependentBean : dependentBeans) {
  67. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  68. actualDependentBeans.add(dependentBean);
  69. }
  70. }
  71. if (!actualDependentBeans.isEmpty()) {
  72. throw new BeanCurrentlyInCreationException(beanName,
  73. "Bean with name '" + beanName + "' has been injected into other beans [" +
  74. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  75. "] in its raw version as part of a circular reference, but has eventually been " +
  76. "wrapped. This means that said other beans do not use the final version of the " +
  77. "bean. This is often the result of over-eager type matching - consider using " +
  78. "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
  79. }
  80. }
  81. }
  82. }
  83. // Register bean as disposable.
  84. try {
  85. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  86. }
  87. catch (BeanDefinitionValidationException ex) {
  88. throw new BeanCreationException(
  89. mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  90. }
  91. return exposedObject;
  92. }
  1. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  2. if (System.getSecurityManager() != null) {
  3. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  4. invokeAwareMethods(beanName, bean);
  5. return null;
  6. }, getAccessControlContext());
  7. }
  8. else {
  9. invokeAwareMethods(beanName, bean);
  10. }
  11. Object wrappedBean = bean;
  12. if (mbd == null || !mbd.isSynthetic()) {
  13. // 应用BeanPostProcessor的初始化前置方法
  14. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  15. }
  16. try {
  17. // 执行初始化方法
  18. invokeInitMethods(beanName, wrappedBean, mbd);
  19. }
  20. catch (Throwable ex) {
  21. throw new BeanCreationException(
  22. (mbd != null ? mbd.getResourceDescription() : null),
  23. beanName, "Invocation of init method failed", ex);
  24. }
  25. if (mbd == null || !mbd.isSynthetic()) {
  26. // 应用BeanPostProcessor的初始化后置方法
  27. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  28. }
  29. return wrappedBean;
  30. }

- Aware接口相关方法执行的时机
  1. protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
  2. if (System.getSecurityManager() != null) {
  3. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  4. invokeAwareMethods(beanName, bean);
  5. return null;
  6. }, getAccessControlContext());
  7. }
  8. else {
  9. // 此处核心,执行Aware方法,主要执行了BeanFactoryAware接口
  10. invokeAwareMethods(beanName, bean);
  11. }
  12. Object wrappedBean = bean;
  13. if (mbd == null || !mbd.isSynthetic()) {
  14. // 此处核心,内部执行Aware方法,主要执行了ApplicationContextAware接口
  15. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  16. }
  17. try {
  18. invokeInitMethods(beanName, wrappedBean, mbd);
  19. }
  20. catch (Throwable ex) {
  21. throw new BeanCreationException(
  22. (mbd != null ? mbd.getResourceDescription() : null),
  23. beanName, "Invocation of init method failed", ex);
  24. }
  25. if (mbd == null || !mbd.isSynthetic()) {
  26. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  27. }
  28. return wrappedBean;
  29. }

BeanFactoryAware接口:

  1. private void invokeAwareMethods(String beanName, Object bean) {
  2. if (bean instanceof Aware) {
  3. if (bean instanceof BeanNameAware) {
  4. ((BeanNameAware) bean).setBeanName(beanName);
  5. }
  6. if (bean instanceof BeanClassLoaderAware) {
  7. ClassLoader bcl = getBeanClassLoader();
  8. if (bcl != null) {
  9. ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
  10. }
  11. }
  12. if (bean instanceof BeanFactoryAware) {
  13. ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
  14. }
  15. }
  16. }

ApplicationContextAware接口相关:

  1. @Override
  2. public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
  3. throws BeansException {
  4. Object result = existingBean;
  5. for (BeanPostProcessor processor : getBeanPostProcessors()) {
  6. Object current = processor.postProcessBeforeInitialization(result, beanName);
  7. if (current == null) {
  8. return result;
  9. }
  10. result = current;
  11. }
  12. return result;
  13. }
  1. @Override
  2. @Nullable
  3. public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
  4. if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
  5. bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
  6. bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
  7. bean instanceof ApplicationStartupAware)) {
  8. return bean;
  9. }
  10. AccessControlContext acc = null;
  11. if (System.getSecurityManager() != null) {
  12. acc = this.applicationContext.getBeanFactory().getAccessControlContext();
  13. }
  14. if (acc != null) {
  15. AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
  16. invokeAwareInterfaces(bean);
  17. return null;
  18. }, acc);
  19. }
  20. else {
  21. invokeAwareInterfaces(bean);
  22. }
  23. return bean;
  24. }
  1. private void invokeAwareInterfaces(Object bean) {
  2. if (bean instanceof EnvironmentAware) {
  3. ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
  4. }
  5. if (bean instanceof EmbeddedValueResolverAware) {
  6. ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
  7. }
  8. if (bean instanceof ResourceLoaderAware) {
  9. ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
  10. }
  11. if (bean instanceof ApplicationEventPublisherAware) {
  12. ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
  13. }
  14. if (bean instanceof MessageSourceAware) {
  15. ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
  16. }
  17. if (bean instanceof ApplicationStartupAware) {
  18. ((ApplicationStartupAware) bean).setApplicationStartup(this.applicationContext.getApplicationStartup());
  19. }
  20. if (bean instanceof ApplicationContextAware) {
  21. ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
  22. }
  23. }

13. finishRefresh()

完成刷新,做收尾工作。

  1. protected void finishRefresh() {
  2. // Clear context-level resource caches (such as ASM metadata from scanning).
  3. clearResourceCaches();
  4. // Initialize lifecycle processor for this context.
  5. initLifecycleProcessor();
  6. // Propagate refresh to lifecycle processor first.
  7. getLifecycleProcessor().onRefresh();
  8. // Publish the final event.
  9. publishEvent(new ContextRefreshedEvent(this));
  10. // Participate in LiveBeansView MBean, if active.
  11. if (!NativeDetector.inNativeImage()) {
  12. LiveBeansView.registerApplicationContext(this);
  13. }
  14. }

1.2 一种特殊的生命周期

此种方式,不经过上述完整的流程即可创建出指定Bean的示例。在一些特殊的需求中可以用到这种方式。
Spring V2 - 图2