SpringBoot使用的ApplicationContext对象类型为:ConfigurableApplicationContext,这是一个接口,有很多实现类。而具体使用哪一个实现类取决于SpringBoot的应用类型webApplicationType(SpringBoot源码之deduceFromClasspath方法推断应用程序类型原理)
具体创建ApplicationContext对象的代码位于:org.springframework.boot.SpringApplication#createApplicationContext
代码如下:
protected ConfigurableApplicationContext createApplicationContext() { Class<?> contextClass = this.applicationContextClass; if (contextClass == null) { try { switch (this.webApplicationType) { case SERVLET: contextClass = Class.forName(DEFAULT_SERVLET_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); } } return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }
可以看到不同webApplicationType类型对应的实现类如下:
SERVLET -> org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
REACTIVE -> org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext
default -> org.springframework.context.annotation.AnnotationConfigApplicationContext
当然你也可以手动通过对applicationContextClass设置指定自定义的实现类。
contextClass类型确定后,SpringBoot就使用反射的形式创建了对应的对象,具体的实现使用的是BeanUtils这个工具类。