When i debug my spring boot application in Intellij IDEA, i found the main method of my spring application will return. When the main method return that means the process has finished, how can the spring boot application still accept requests?
Asked
Active
Viewed 1,042 times
1
-
4Probably because it started some background threads that keep the JVM alive...? – ernest_k Mar 15 '18 at 08:10
-
@ErnestKiwele Do you know where the application start those background threads? – HongyanShen Mar 15 '18 at 08:12
-
When you launch your application, the web server/container is started by spring-boot. And the containers have thread pools and a lot of mechanisms to keep the application running, exactly to wait for incoming requests... You need to find in the documentation how to stop a spring boot application. – ernest_k Mar 15 '18 at 08:15
-
@ErnestKiwele I just wander how the spring boot application works,because in other web frameworks Eg. Flask, NodeJs Express, When we run app.Run(), the application will block to accept requests, which is easy to understand, because three is an event loop or listener to listen and accept connections, then the application can work.However, It seems that the spring boot application will never block to listen and accept connections. – HongyanShen Mar 15 '18 at 08:26
1 Answers
2
At the time you include a web-starter
as a dependency for your application, Spring Boot knows it has to start an embeded servlet container (web server), unless you 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>
Then when you do:
@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);
}
}
The line SpringApplication.run(SampleController.class, args);
evaluates the classpath dependencies being included and detects the web dependencies. Then it knows you're configuring a web application and instantiates the servlet container, which keeps accepting requests until you explicitly terminate it.
Samples:
See also:

Aritz
- 30,971
- 16
- 136
- 217
-
So i guess the spring boot just start a tomcat server asynchronously and copy the resources to the work directory of the server, then the server can handle requests with those resources, am i right? – HongyanShen Mar 15 '18 at 08:46
-
Yes, I'm not sure if it does copy the resources or just configure tomcat to point it to an external work directory with its resources instead, but that's how it works. – Aritz Mar 15 '18 at 08:59
-
1