初探SpringBoot启动原理

image-20231109185524452

SpringApplication

1
2
3
4
5
6
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
//从这个方法可以看出Spring启动过成可以分为两个部分
//1、创建SpringApplication对象
//2、运行

1、创建SpringApplication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//判断当前web的类型,WebApplicationType.SERVLET,并存入webApplicationType属性中
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//初始启动器,去Spring.factories文件中查找启动器, org.springframework.boot.Bootstrapper
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class));
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//找到主程序,包含main方法的程序,将主程序存到mainApplicationClass属性中
this.mainApplicationClass = deduceMainApplicationClass();
}
  • this.bootstrapRegistryInitializers = new ArrayList<>(getSpringFactoriesInstances(BootstrapRegistryInitializer.class));

    • 会在Spring.factories文件中查找org.springframework.boot.BootstrapRegistryInitializer
    • 并将查找到的组件存放在SpringApplication对象的 bootstrapRegistryInitializers
  • setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));

    • 会在Spring.factories文件中查找org.springframework.context.ApplicationContextInitializer

    • 将查找的组件保存在SpringApplication对象的 initializers

    • image-20231107154431058

    • image-20231107154158440

    • image-20231107154359136

  • setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));

    • 会在Spring.factories文件中查找监听器org.springframework.context.ApplicationListener

    • 并将查找到的组件保存在SpringApplication对象的listeners

    • image-20231107155100010

    • image-20231107155134753

    • image-20231107155157262

2、运行SpringApplication

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
public ConfigurableApplicationContext run(String... args) {
//记录应用的启动时间
long startTime = System.nanoTime();
//创建引导上下文
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
//保存命令行参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//准备环境
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
//配置需要忽略的配置信息
configureIgnoreBeanInfo(environment);
//在控制台打印SpringBoot Banner
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);
}
listeners.started(context, timeTakenToStartup);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
}
catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
  • DefaultBootstrapContext bootstrapContext = createBootstrapContext() 创建引导上下文

    • 获取之前所有存放在SpringApplication对象中的bootstrapRegistryInitializers中的值,遍历调用initialize进行初始化,来完成对启动上下文的设置
  • configureHeadlessProperty(); 设置java.awt.headless 属性,让当前应用进入headless模式

  • getRunListeners(args),获取所有运行时监听器

    • 去Spring.factories文件中查找SpringApplicationRunListener

    • image-20231107161854341

    • image-20231107161916535

  • listeners.starting(bootstrapContext, this.mainApplicationClass);

    • 遍历所有SpringApplicationRunListeners,调用listener.starting(bootstrapContext)方法完成listener初始化,这个方法允许你在应用程序启动的早期阶段进行一些自定义设置或操作
  • prepareEnvironment(listeners, bootstrapContext, applicationArguments); 准备所有的环境信息

    • ConfigurableEnvironment environment = getOrCreateEnvironment();,根据webApplicationType中的值返回一个对应的环境

      因为时servlet环境所以返回一个servlet环境

    • 配置返回的servlet环境环境

      • configurePropertySources(environment, args); 加载应用程序的配置属性,包括外部属性文件和默认属性
      • 为应用程序设置活动的配置文件(Profile)。
    • 绑定属性值

    • environmentPrepared(),用于执行一些需要在应用程序启动前对配置属性进行干预的情况

  • createApplicationContext();创建ioc容器

    • 根据当前web应用的类型创建ioc容器/beang工厂
      • image-20231107165638552
  • prepareContext(),准备ioc容器基本信息

    • 保存环境信息

    • postProcessApplicationContext(context) ioc的后置处理,添加类型转换器 。。。

    • applyInitializers(),应用程序初始化器

      • 遍历所有SpringApplication对象的ApplicationContextInitializer来完成对ioc容器初始化的扩展
    • listeners.contextPrepared(context)遍历所有的SpringApplicationRunListeners,调用contextLoaded()

      • image-20231107175515230
    • springApplicationArguments、springBootBanner、日志相关组件存放到单例池中

    • listeners.contextLoaded(context);遍历所有SpringApplicationRunListeners,调用contextLoaded()方法的扩展 Spring Boot 应用程序的启动过程

  • refreshContext(context); 刷新Ioc容器,创建和初始化bean

Spring生命周期分析

refreshContext(context); 刷新Ioc容器,创建和初始化bean

1
2
3
protected void refresh(ConfigurableApplicationContext applicationContext) {
applicationContext.refresh();
}

AbstractApplicationContext

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
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
this.prepareRefresh();
//刷新bean工厂
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
//准备bean工厂
this.prepareBeanFactory(beanFactory);

try {
this.postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
//注册所有的后置处理器
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
//调用been工厂完成bean的初始化和实例化
this.finishBeanFactoryInitialization(beanFactory);
//发布相应事件
this.finishRefresh();
} catch (BeansException var10) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var10);
}
//销毁
this.destroyBeans();
this.cancelRefresh(var10);
throw var10;
} finally {
this.resetCommonCaches();
contextRefresh.end();
}

}
}
  • prepareRefresh(); 刷新ioc容器的准备阶段

    • 清除包扫描缓存资源
    • 初始化属性源
  • prepareBeanFactory(beanFactory);,准备bean工厂

    • ```java
      ….
      beanFactory.setBeanClassLoader(getClassLoader());
      if (!shouldIgnoreSpel) {
      beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
      }
      beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

      // Configure the bean factory with context callbacks.
      beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
      beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
      beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
      beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
      beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
      beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
      beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
      beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);

      // BeanFactory interface not registered as resolvable type in a plain factory.
      // MessageSource registered (and found for autowiring) as a bean.
      beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
      beanFactory.registerResolvableDependency(ResourceLoader.class, this);
      beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
      beanFactory.registerResolvableDependency(ApplicationContext.class, this);

      // Register early post-processor for detecting inner beans as ApplicationListeners.
      beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
      ….

      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
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62

      - 配置bean工厂

      - 设置ClassLoader、后处理器
      - 添加 ApplicationContextAwareProcessor 作为 Bean 后置处理器,这样在初始化 Bean 时可以将当前应用程序上下文传递给实现 ApplicationContextAware 接口的 Bean。这样,这些 Bean 可以访问应用程序上下文以获取其他 Bean 和资源。
      - 忽略一些依赖接口、注册可解析的依赖类型
      - 注册应用程序监听器检测器
      - 将一些默认环境注册为一个bean

      - postProcessBeanFactory(beanFactory);bean工厂后处理

      - 添加一些后处理器、注册web应用程序作用域

      - invokeBeanFactoryPostProcessors(beanFactory);

      - 调用BeanFactoryPostProcessors,来对bean进行额外的配置
      - 添加属性配置、修改Bean定义,封装beanDefinitionNames、调用并注册在应用程序上下文中的 BeanFactory 后处理器
      - ![image-20231108030517617](https://myblog-imag.oss-cn-guangzhou.aliyuncs.com/blogImg/image-20231108030517617.png)

      - registerBeanPostProcessors(beanFactory); 注册 Bean 后处理器

      - ![image-20231109142412378](https://myblog-imag.oss-cn-guangzhou.aliyuncs.com/blogImg/image-20231109142412378.png)

      - initMessageSource();初始化源,一般用来处理国际化

      - ![image-20231109150814060](https://myblog-imag.oss-cn-guangzhou.aliyuncs.com/blogImg/image-20231109150814060.png)

      - initApplicationEventMulticaster(); 初始化事件监听器监听器

      - ![image-20231109150825100](https://myblog-imag.oss-cn-guangzhou.aliyuncs.com/blogImg/image-20231109150825100.png)

      - onRefresh();注册一些特殊类型的bean (tomcat,servlet)

      - finishBeanFactoryInitialization(beanFactory);创建和初始化bean

      #### **finishBeanFactoryInitialization()**

      ```java
      protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
      if (beanFactory.containsBean("conversionService") && beanFactory.isTypeMatch("conversionService", ConversionService.class)) {
      beanFactory.setConversionService((ConversionService)beanFactory.getBean("conversionService", ConversionService.class));
      }

      if (!beanFactory.hasEmbeddedValueResolver()) {
      beanFactory.addEmbeddedValueResolver((strVal) -> {
      return this.getEnvironment().resolvePlaceholders(strVal);
      });
      }

      String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
      String[] var3 = weaverAwareNames;
      int var4 = weaverAwareNames.length;

      for(int var5 = 0; var5 < var4; ++var5) {
      String weaverAwareName = var3[var5];
      this.getBean(weaverAwareName);
      }

      beanFactory.setTempClassLoader((ClassLoader)null);
      beanFactory.freezeConfiguration();
      beanFactory.preInstantiateSingletons(); //实例化单例bean
      }

进入 preInstantiateSingletons();

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
52
53
54
55
56
57
58
59
60
61
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}

//获取所有的bean的名字
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
//根据beanname取出BeanDefinition,bean的定义类
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//判断这个bean是否抽象,单例,懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
//判断是否是工厂bean实例化
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
//不是工程bean则进去这方法
getBean(beanName);
}
}
}

// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
.tag("beanName", beanName);
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
smartInitialize.end();
}
}
}
  • isFactoryBean(beanName)

    • 根据beanname 从singletonObjects(单例池)获取这个bean如果能获取到这个bean则代表这个bean已经在前面实例化了
    • 如果在单例池中没有存在这个bean,则检查bean的定义,根据bean定义判断是否是FactoryBean实例
    • 如果单例池中存在了这个bean,判断这个bean是否是FactoryBean的实例
    • 如果这个bean是FactoryBean的实例则返回true,否则返回false
  • getBean(beanName);获取bean,根据beanname在单例池中去查找判断是否存在这个bean

    • 如果在单例池中能获取到bean,则直接返回这个bean

    • 如果不存在这个bean,

      • 将这个beanname添加到alreadyCreated中,将这个bean标记为已创建

      • 准备开始bean的实例化

        • 获取并检查bean的定义、判断是否是抽象,如果是抽象的则抛出异常

        • mbd.getDependsOn(),获取这个bean的依赖关系,如果不为空初始化当前bean所依赖的bean

          • String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                        "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }
            
            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

            - 调用createBean方法创建bean

            - 在实例化前会调用resolveBeforeInstantiation方法进行解析,会调用前置处理器和后置处理器进行处理

            - 调用实现了**InstantiationAwareBeanPostProcessor**接口类的前置处理器**postProcessBeforeInstantiation**方法进行实例化前处理

            - ```java
            protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
            Object bean = null;
            if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
            // Make sure bean class is actually resolved at this point.
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
            //实例化前bean处理器
            bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
            if (bean != null) {
            bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
            }
            }
            }
            mbd.beforeInstantiationResolved = (bean != null);
            }
            return bean;
            }

            protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
            for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
            Object result = bp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
            return result;
            }
            }
            return null;
            }
          • 最后调用doCreateBean方法来完成bean的创建

          • 如果是单例bean,会将创建完成的bean放到单例池中

doCreateBean()

AbstractAutowireCapableBeanFactory.class

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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

//bean的包装器
BeanWrapper instanceWrapper = null;
//单例
if (mbd.isSingleton()) {
//从缓存中删除这个bean实例
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//创建bean实例,并封装成一个包装器
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//从包装器中拿到这个bean
Object bean = instanceWrapper.getWrappedInstance();
//从包装器中获取这个实例的类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}


synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//应用合并的bean处理器
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}

//判断这个bean是否单例,是否允许循环引用,是否是当前正在创建的单例
//this.allowCircularReferences = false
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
//false
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
//填充bean属性
populateBean(beanName, mbd, instanceWrapper);
//执行初始化方法
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}

// 。。。。

// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}
  • createBeanInstance 创建bean实例
    • 确定构造方法-遍历构造方法,查找构造方法上是否有,Autowired注解
    • instantiateBean,用默认构造实例化该bean
    • 解析构造方法,利用反射通过构造方法去创建对象
      • image-20231109164254489
  • populateBean()填充bean属性
  • initializeBean() 初始化bean

populateBean()

  • 调用实现了InstantiationAwareBeanPostProcessor接口类的后置处理器postProcessAfterInstantiation方法进行实例后处理

    • ```java
      if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
      if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
      return;
      }
      }
      }
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18

      - 调用实现了**InstantiationAwareBeanPostProcessor**接口类的**postProcessProperties**方法进行属性处理

      - ```java
      //依次调用处理器来完成属性的赋值
      for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
      PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
      if (pvsToUse == null) {
      if (filteredPds == null) {
      filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      }
      pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
      if (pvsToUse == null) {
      return;
      }
      }
      pvs = pvsToUse;
      }

image-20231109165942965

initializeBean()

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
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//调用Aware方法,如果这个bean是xxxAware的实例则会调用相应方法
invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//调用初始化bean的的后置处理器
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
//调用init方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

return wrappedBean;
}
  • applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);,调用初始化bean前的处理器

    • image-20231109171047209
  • invokeInitMethods(beanName, wrappedBean, mbd); ,执行初始化方法

    • //判断这个bean是否实现了InitializingBean方法,如果实现则返回true
      boolean isInitializingBean = (bean instanceof InitializingBean);
      if (isInitializingBean && (mbd == null || !mbd.hasAnyExternallyManagedInitMethod("afterPropertiesSet"))) {
          if (logger.isTraceEnabled()) {
              logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
          }
          if (System.getSecurityManager() != null) {
              try {
                  AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                      ((InitializingBean) bean).afterPropertiesSet();
                      return null;
                  }, getAccessControlContext());
              }
              catch (PrivilegedActionException pae) {
                  throw pae.getException();
              }
          }
          else {
              //调用bean的afterPropertiesSet()方法
              ((InitializingBean) bean).afterPropertiesSet();
          }
      }
      
      //bean
      @Override
      public void afterPropertiesSet() throws Exception {
          System.out.println("service...init");
      }
      
  • applyBeanPostProcessorsAfterInitialization()实例化后处理器

    • image-20231109184718823

    • 遍历,依次调用后置处理器,进行后置处理

总结

四个主要阶段

  1. 实例化(Instantiation)
  2. 属性赋值(Populate)
  3. 初始化(Initialization)
  4. 销毁(Destruction)

图一

在这里插入图片描述

图二

image-20231112234057038