SpringBoot實戰分析(六)創建應用程序上下文

程序入口

context = createApplicationContext();

斷點跟蹤

1.判斷環境類型和初始化

當前方法默認加載的是

org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext這個類。

protected ConfigurableApplicationContext createApplicationContext() {
    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);
            }
        }
  省略。。。。。。
    }
    return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}

contextClass的值域:


2.實例化類

獲取AnnotationConfigServletWebServerApplicationContext聲明的構造器,然後去按照構造器實例化。

public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {
    Assert.notNull(clazz, "Class must not be null");
    if (clazz.isInterface()) {
        throw new BeanInstantiationException(clazz, "Specified class is an interface");
    }
    try {
        // 走clazz.getDeclaredConstructor()方法
        Constructor<T> ctor = (KotlinDetector.isKotlinType(clazz) ?
                KotlinDelegate.getPrimaryConstructor(clazz) : clazz.getDeclaredConstructor());
        return instantiateClass(ctor);
    }
    省略。。。。。。
}

public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
    Assert.notNull(ctor, "Constructor must not be null");
    try {
        ReflectionUtils.makeAccessible(ctor);
        //走ctor.newInstance(args))方法
        return (KotlinDetector.isKotlinType(ctor.getDeclaringClass()) ?
                KotlinDelegate.instantiateClass(ctor, args) : ctor.newInstance(args));
    }
省略。。。。。。
}

3.返回context






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章