How to start the built-in servlet container in Spring Boot?
Spring Boot comes with several common Servlet containers built-in, such as Tomcat and Jetty. Starting these embedded Servlet containers is very simple – just add the `@SpringBootApplication` annotation to the main class of your Spring Boot application, and call the `SpringApplication.run` method in the main method.
Here is an example code:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
In this example, MyApplication is the entry class of the Spring Boot application. The @SpringBootApplication annotation includes features such as auto-configuration, component scanning, and enabling Spring Boot capabilities. The SpringApplication.run method in the main method will start the embedded Servlet container and load the application’s configuration.
After launching the application, Spring Boot will choose the appropriate Servlet container based on the settings in the configuration file and deploy the application to that container. By default, Spring Boot uses Tomcat as the built-in Servlet container. If you want to use another Servlet container, you can add the corresponding dependency in the pom.xml file and exclude the dependency for Tomcat.
For example, if you want to use Jetty as the built-in Servlet container, you can add the following dependency in the pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Then, in the main method, call the SpringApplication.run method to start the application, Spring Boot will automatically use Jetty as the embedded Servlet container.
In summary, starting the built-in Servlet container in Spring Boot is very simple, just add the necessary annotations in the main class and call the SpringApplication.run method.