您的位置:首页 > 编程语言 > Java开发

SpringBoot实战分析(六)创建应用程序上下文

2018-06-19 16:35 344 查看

程序入口

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






阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: