在简单的Spring Boot应用程序中使用了哪个ApplicationContext实现?

时间:2019-01-23 16:12:47

标签: java spring spring-boot

我了解到:

  

“应用上下文”的三种常用实现是-

     

FileSystemXmlApplicationContext-此容器加载定义   XML文件中的Bean数量。在这里您需要提供完整的路径   XML bean配置文件传递给构造函数。

     

ClassPathXmlApplicationContext-此容器加载定义   XML文件中的Bean数量。在这里您不需要提供   XML文件的完整路径,但是您需要正确设置CLASSPATH   因为此容器将在其中查找bean配置XML文件   CLASSPATH。

     

WebXmlApplicationContext-此容器使用以下命令加载XML文件   Web应用程序中所有bean的定义。

那么Spring Boot呢?我读过一些文章,如何获取ApplicationContext:

  

公共类A实现ApplicationContextAware {

private ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
}
     

}

但是Spring Boot中到底使用了哪种应用上下文上下文?

3 个答案:

答案 0 :(得分:1)

Spring Boot应用程序的入口点是一个SpringApplication对象。您可以通过其setApplicationContextClass(Class)方法选择要使用的实现。它的javadoc状态

  

设置将创建的Spring ApplicationContext的类型。如果   对于Web,未指定的默认值为DEFAULT_SERVLET_WEB_CONTEXT_CLASS   基于应用程序或AnnotationConfigApplicationContext(对于非Web应用程序)   基础的应用程序。

其中列出了defaults(如果您不使用该方法),即

org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext

用于基于Web的应用程序和

org.springframework.context.annotation.AnnotationConfigApplicationContext

用于非基于Web的应用程序。

还有一个default for reactive web environments

答案 1 :(得分:0)

Spring Boot创建一种称为ApplicationContext的新型WebServerApplicationContext,它与嵌入式服务器集成在一起。它进一步分为两种实现类别,一种用于Servlet堆栈(ServletWebServerApplicationContext),另一种用于Webflux反​​应式堆栈(ReactiveWebServerApplicationContext)。

此新上下文的显着区别是,它将在引导上下文期间创建和管理嵌入式服务器。因此,您可以看到此上下文将返回一个具有以下接口的WebServer

public interface WebServer {
    void start() throws WebServerException;
    void stop() throws WebServerException;
    int getPort();
}

WebServer可以是JettyWebServerNettyWebServerTomcatWebServerUndertowWebServer等,这取决于在类路径中找到哪个嵌入式服务器。

答案 2 :(得分:0)

这取决于您的类路径,例如,如果您正在创建Web应用程序,则它可能是AnnotationConfigWebApplicationContext

获取ApplicationContext并在其上应用方法getClass()来检查其实现。