【问题标题】:Why the main method of spring boot application has returned but the application still can accept requests? [closed]为什么spring boot应用程序的main方法已经返回,但应用程序仍然可以接受请求? [关闭]
【发布时间】:2018-08-23 23:02:48
【问题描述】:

当我在 Intellij IDEA 中调试我的 spring boot 应用程序时,我发现我的 spring 应用程序的 main 方法将返回。当main方法返回表示进程已经结束,spring boot应用怎么还能接受请求呢?

【问题讨论】:

  • 可能是因为它启动了一些让 JVM 保持活动状态的后台线程...?
  • @ErnestKiwele 你知道应用程序在哪里启动那些后台线程吗?
  • 当你启动你的应用程序时,web server/container 由 spring-boot 启动。并且容器具有线程池和许多机制来保持应用程序运行,确切地说是等待传入的请求......您需要在文档中找到如何停止 Spring Boot 应用程序。
  • @ErnestKiwele 我只是想知道 Spring Boot 应用程序是如何工作的,因为在其他 Web 框架中,例如。 Flask,NodeJs Express,当我们运行app.Run()时,应用程序会阻塞接受请求,这很容易理解,因为三是一个事件循环或者监听器来监听和接受连接,那么应用程序就可以工作了。但是,看来spring boot应用永远不会阻塞监听和接受连接。

标签: java spring spring-mvc spring-boot


【解决方案1】:

当您包含 web-starter 作为应用程序的依赖项时,Spring Boot 知道它必须启动一个嵌入式 servlet 容器(Web 服务器),除非您 explicitly tell him not to do it

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

那么当你这样做时:

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

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

SpringApplication.run(SampleController.class, args); 行评估包含的类路径依赖项并检测 Web 依赖项。然后它知道您正在配置一个 Web 应用程序并实例化 servlet 容器,该容器会一直接受请求,直到您明确终止它。

样本:

另请参阅:

【讨论】:

  • 所以我猜spring boot只是异步启动一个tomcat服务器并将资源复制到服务器的工作目录,然后服务器可以处理这些资源的请求,对吗?
  • 是的,我不确定它是复制资源还是只是配置 tomcat 以将其指向具有其资源的外部工作目录,但这就是它的工作原理。
  • 非常感谢,你把我从困惑中解救了出来。
猜你喜欢
  • 2016-07-29
  • 1970-01-01
  • 2019-02-12
  • 2021-08-13
  • 2019-02-02
  • 2014-05-21
  • 2023-03-19
  • 1970-01-01
  • 2019-08-01
相关资源
最近更新 更多