欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot启动-构造ApplicationContext

程序员文章站 2022-05-25 11:54:53
...

创建ApplicationContext实现代码如下:

  1. 根据Web应用类型,获取对应的ApplicationContext子类
  2. 实例化ApplicationContext子类
// 常量定义
public static final String DEFAULT_WEB_CONTEXT_CLASS = "org.springframework.boot."
            + "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
            + "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";
public static final String DEFAULT_CONTEXT_CLASS = "org.springframework.context."
            + "annotation.AnnotationConfigApplicationContext";

    protected ConfigurableApplicationContext createApplicationContext() {
        // 1. 根据Web应用类型,获取对应的ApplicationContext子类
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch (this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
                    break;
                case REACTIVE:
                    contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
                    break;
                default:
                    contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
                }
            }
            catch (ClassNotFoundException ex) {
                throw new IllegalStateException(
                        "Unable create a default ApplicationContext, "
                                + "please specify an ApplicationContextClass",
                        ex);
            }
        }
        // 2. 实例化子类
        return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    }

BeanFactory也是在此过程中被创建

    public GenericApplicationContext() {
        this.beanFactory = new DefaultListableBeanFactory();
    }