Using Embedded Jetty Server For Spring Boot Application

By default, the spring boot web starter uses an embedded tomcat server. In this article, we will learn how to use an embedded jetty server instead of the default tomcat server in the spring boot application.

Table of Contents

Adding jetty server to the spring application

Create a new spring boot application, and add the below maven dependency.

Also, to enable the jetty server in the spring application, we have to exclude tomcat server dependency in our pom xml file.

Then we have to add spring boot starter jetty dependency as given below.

<dependencies>
		<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>
</dependencies>

We can also use the gradle build tool as shown below.

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")
}

Jetty server spring boot configuration properties

A few of the jetty server configuration properties are shown below.

These are a few of the supported application.properties. Click here for all available properties list.

server.port=8081
server.servlet.context-path=/app

server.jetty.accesslog.append=true # Append to log.
server.jetty.accesslog.date-format=dd/MMM/yyyy:HH:mm:ss Z # Timestamp format of the request log.
server.jetty.accesslog.enabled=true # Enable access log.

Jetty server programmatic Customization

We can implement the WebServerFactoryCustomizer interface to customize server configuration.

Below is the programmatic customization of the server port and also the application context path.

@SpringBootApplication
public class SpringBootJettyApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

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

	@Override
	public void customize(ConfigurableServletWebServerFactory factory) {
		factory.setPort(9000);
		factory.setContextPath("/myapp");
	}
}

Congratulations!! We have configured an embedded Jetty server for our spring application! ๐Ÿ™‚ Also, letโ€™s run the application. ๐Ÿ™‚

We can be able to see the server is getting started with configured server configuration.

spring boot jetty configuration example

Conclusion

In conclusion, in this article, we learned about how to use an embedded jetty server in the spring application.

Happy coding!! ๐Ÿ™‚ ๐Ÿ™‚