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

To enable jetty server in spring boot 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 use 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 configuration properties

Few of the jetty server configuration properties shown below. These are 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 WebServerFactoryCustomizer interface to customize server configuration.

Below is the programmatic customization of server port and 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 embedded Jetty server for our spring boot application! ๐Ÿ™‚ Let us run the application. ๐Ÿ™‚

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

spring boot jetty configuration example

Conclusion

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

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

You may also interested in