什么是默认的 Spring Boot 应用程序上下文?

bwo*_*e12 4 java spring spring-boot

在 Spring Framework 中,我们可以从下图中选择应用程序上下文的类型:

Spring 应用程序上下文类型

但是spring boot默认实现的是哪一个呢?

它是否取决于我们在创建项目时选择的启动器依赖项?

Rol*_*der 6

这取决于您使用的入门项目。对于常规项目,Spring Boot 使用AnnotationConfigApplicationContext,对于 Web 项目使用AnnotationConfigServletWebServerApplicationContext

另见输出

@SpringBootApplication
public class DummyApplication implements ApplicationContextAware {

    public static void main(String[] args) {
        SpringApplication.run(DummyApplication.class, args);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        System.out.println(applicationContext.getClass().getName());
    }
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*han 5

从技术上讲,它不直接取决于启动器,而是取决于WebApplicationType您配置运行应用程序的值:

public static void main(String[] args) throws Exception {
  SpringApplication app = new SpringApplication(FooApplication.class);
  app.setWebApplicationType(WebApplicationType.SERVLET);
  app.run(args);
}
Run Code Online (Sandbox Code Playgroud)

如果不配置它,将通过检查类路径中是否存在某些类来推导出默认值。

有 3 种类型的WebApplicationType遗嘱是REACTIVESERVLETNONE

并且根据它的值,它将选择要为其创建的应用程序上下文类型。看到这个逻辑。

  • 对于REACTIVE,它将创建AnnotationConfigReactiveWebServerApplicationContext
  • 对于SERVLET,它将创建AnnotationConfigServletWebServerApplicationContext
  • 对于NONE,它将创建AnnotationConfigApplicationContext

因此,即使您使用某些 starter 也是可能的,但更改 WebApplicationType 值将导致使用不同的上下文类型。