By default, Spring boot uses the embedded Tomcat server to run the application. At times, we may need to use Jetty server in place of Tomcat server. Spring Boot bundles Tomcat and Jetty dependencies as separate starters to help make this process as easy as possible. We can use the jetty by following simple steps.
1. Add spring-boot-starter-jetty Dependency
We will need to update pom.xml
and add the dependency for spring-boot-starter-jetty
. Also, you will need to exclude the default added spring-boot-starter-tomcat
dependency.
<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>
In Gradle, this change can be achieved by this:
configurations {
compile.exclude module: "spring-boot-starter-tomcat"
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web:2.0.0.BUILD-SNAPSHOT")
compile("org.springframework.boot:spring-boot-starter-jetty:2.0.0.BUILD-SNAPSHOT")
}
2. Override Jetty Default Configuration
To override the default runtime configuration for Jetty, we can configure the properties in application.properties
file.
server.port=8080
server.servlet.context-path=/home
####Jetty specific properties########
server.jetty.acceptors= # Number of acceptor threads to use.
server.jetty.max-http-post-size=0 # Maximum size in bytes of the HTTP post or put content.
server.jetty.selectors= # Number of selector threads to use.
Also, we may configure these options programmatically using JettyEmbeddedServletContainerFactory
bean.
@Bean
public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory() {
JettyEmbeddedServletContainerFactory jettyContainer =
new JettyEmbeddedServletContainerFactory();
jettyContainer.setPort(9000);
jettyContainer.setContextPath("/home");
return jettyContainer;
}
3. Update for Spring Boot 2
The above code snippet was valid for the spring boot spanshot version. After Spring boot 2.0.0.RELEASE is available, we shall be using ConfigurableServletWebServerFactory and JettyServletWebServerFactory classes.
@Bean
public ConfigurableServletWebServerFactory webServerFactory()
{
JettyServletWebServerFactory factory = new JettyServletWebServerFactory();
factory.setPort(9000);
factory.setContextPath("/myapp");
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html"));
return factory;
}
Drop me your questions in the comments section related to using jetty instead of tomcat server in any spring boot application.
Happy Learning !!
Ref: Configure Jetty