Changing the embedded server in a Spring Boot application is a straightforward process, thanks to Spring Boot’s auto-configuration. By default, Spring Boot uses Tomcat as the embedded servlet container, but it can be easily switched to other servers such as Jetty or Undertow. Here’s how you can change the embedded server:
Step 1: Exclude the Default Tomcat Dependency
First, you need to exclude the default Tomcat dependency from your spring-boot-starter-web
dependency in your pom.xml
(Maven) or build.gradle
(Gradle) file.
For Maven:
<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>
For Gradle:
implementation('org.springframework.boot:spring-boot-starter-web') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
Step 2: Add Dependency for the Desired Embedded Server
Next, add the dependency for the embedded server you want to use, such as Jetty or Undertow.
For Jetty with Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
For Jetty with Gradle:
implementation 'org.springframework.boot:spring-boot-starter-jetty'
For Undertow with Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
For Undertow with Gradle:
implementation 'org.springframework.boot:spring-boot-starter-undertow'
Step 3: Verify the Configuration
After adding the desired server dependency, Spring Boot auto-configures the application to use it as the default embedded servlet container. No further configuration is usually needed unless you have specific requirements for the new server.
Optional: Server-Specific Configuration
If you need to customize the server configuration, you can do so in your application.properties
or application.yml
file. Each server has its own set of properties that can be configured. For example, to set the port for Jetty:
server.port=8080
Or for Undertow, to configure the number of I/O threads:
server.undertow.io-threads=4
Changing the embedded server in Spring Boot allows developers to tailor the servlet container to their specific needs, taking advantage of the unique features and performance characteristics of each server.