How Spring Boot bootstraps its embedded web server
A Spring Boot application starts its own web server from main: it picks the application type, creates the context, builds Tomcat from a factory bean and opens the port only when every bean is ready. This page runs that sequence event by event, builds the same server by hand for comparison, and then configures compression, limits, virtual threads and graceful shutdown.
Contents
How Spring Boot starts an embedded web server
A traditional Java web application is packaged as a WAR file and deployed into a server that is already running, such as Tomcat. Spring Boot reverses this: the server is a library inside the application, started from main
When SpringApplication.run
- Deciding the application type: Spring Boot looks at the classpath. With Spring MVC and the Servlet API present it creates a servlet web application; with only Spring WebFlux, a reactive one; with neither, a plain application without a server.
overrides the guess.spring.main.web-application-type - Preparing the environment: properties, profiles and logging are set up, before any bean exists.
- Creating the context: for a servlet application, an
, which knows how to create a web server during its refresh.AnnotationConfigServletWebServerApplicationContext - Creating the server: during the refresh, the context looks up the
bean that auto-configuration provides, by default aServletWebServerFactory . Customizers applyTomcatServletWebServerFactory properties to it, and it builds an embedded Tomcat.server.* - Registering servlets and filters: every
bean is applied to the new servlet context. This is how theServletContextInitializer is mapped toDispatcherServlet and how filter beans are added./ - Opening the port: at the end of the refresh, after all singleton beans have been created, the connector starts listening. Requests cannot arrive while beans are still being built.
| Server | How to get it | Notes |
|---|---|---|
| Tomcat 11 | Included in spring-boot-starter-webmvc | The default; used by every example on this page except the Jetty one |
| Jetty 12 | Exclude spring-boot-starter-tomcatspring-boot-starter-jetty | Same server.*server.jetty.* |
| Undertow | No longer available | Removed in Spring Boot 4.0 |
| Reactor Netty | Included in spring-boot-starter-webflux | For reactive applications only |
The programs use Spring Boot 4.1 with Spring Framework 7.0 and Tomcat 11, with spring-boot-starter-webmvc
The startup sequence, event by event
Spring Boot publishes an event at each stage of startup and shutdown, which makes the sequence visible. The listener is added to SpringApplication
package demo.startup;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.boot.web.server.context.WebServerInitializedEvent;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.support.ServletRequestHandledEvent;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class StartupSequence {
@RestController
static class Hello {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(StartupSequence.class);
app.setDefaultProperties(Map.of(
"server.port", "0", "spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
// Added here, not as a bean, so that it also sees the events before the context exists
app.addListeners((ApplicationListener<ApplicationEvent>) event -> {
String name = event.getClass().getSimpleName();
String extra = "";
if (event instanceof WebServerInitializedEvent) {
extra = " (port is now known)";
} else if (event instanceof AvailabilityChangeEvent<?> change) {
extra = " -> " + change.getState();
} else if (event instanceof ServletRequestHandledEvent) {
return; // one per request; left out to keep the output short
}
System.out.println(" event " + name + extra);
});
System.out.println("SpringApplication.run starts");
ConfigurableApplicationContext context = app.run(args);
System.out.println("SpringApplication.run returned");
WebServer server = ((WebServerApplicationContext) context).getWebServer();
System.out.println("context class: " + context.getClass().getSimpleName());
System.out.println("web server : " + server.getClass().getSimpleName());
int status = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
URI.create("http://localhost:" + server.getPort() + "/hello")).build(),
BodyHandlers.ofString()).statusCode();
System.out.println("GET /hello -> " + status);
System.out.println("closing the context");
context.close();
System.out.println("closed");
}
}
SpringApplication.run starts
event ApplicationStartingEvent
event ApplicationEnvironmentPreparedEvent
event ApplicationContextInitializedEvent
event ApplicationPreparedEvent
event ServletWebServerInitializedEvent (port is now known)
event ContextRefreshedEvent
event ApplicationStartedEvent
event AvailabilityChangeEvent -> CORRECT
event ApplicationReadyEvent
event AvailabilityChangeEvent -> ACCEPTING_TRAFFIC
SpringApplication.run returned
context class: AnnotationConfigServletWebServerApplicationContext
web server : TomcatWebServer
GET /hello -> 200
closing the context
event AvailabilityChangeEvent -> REFUSING_TRAFFIC
event ContextClosedEvent
closed
andApplicationStartingEvent came before any bean or context existed. Code that must run this early, such as a custom logging setup, has to be registered this way or inApplicationEnvironmentPreparedEvent .META-INF/spring.factories andApplicationContextInitializedEvent mark the context created and its bean definitions loaded, still without a server.ApplicationPreparedEvent arrived once Tomcat was listening, and is the first point where the real port ofServletWebServerInitializedEvent is known. Tests and service registries read the port from this event.server.port=0 came after the refresh, andApplicationStartedEvent after theApplicationReadyEvent andCommandLineRunner beans had run, of which this program has none.ApplicationRunner- The two
s set the liveness state toAvailabilityChangeEvent and then the readiness state toCORRECT . On close, readiness changed toACCEPTING_TRAFFIC before the context closed. Kubernetes probes in Spring Boot Actuator report these states.REFUSING_TRAFFIC - The context class was
and the server aAnnotationConfigServletWebServerApplicationContext , as the type detection predicted.TomcatWebServer
The listener also receives a ServletRequestHandledEventApplicationReadyEvent
What Spring Boot automates: a server built by hand
To see what the auto-configuration saves, this program builds the same kind of application without Spring Boot. It uses only Spring Framework and the embedded Tomcat library, both of which come with the webmvc starter:
package demo.manual;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import java.io.File;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.util.logging.LogManager;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
// The same kind of application as with Spring Boot, assembled by hand
public class ManualTomcat {
@RestController
static class Hello {
@GetMapping("/hello")
public String hello() {
return "hello from a hand-built server";
}
}
@Configuration
@EnableWebMvc // registers the MVC infrastructure beans
@Import(Hello.class)
static class WebConfig {}
public static void main(String[] args) throws Exception {
quietLogging();
File baseDir = Files.createTempDirectory("tomcat").toFile();
// 1. The Spring application context for the web layer
var spring = new AnnotationConfigWebApplicationContext();
spring.register(WebConfig.class);
// 2. An embedded Tomcat with one connector on a free port
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir(baseDir.getAbsolutePath());
tomcat.setPort(0);
tomcat.getConnector(); // creates the default HTTP connector
// 3. A servlet context with the DispatcherServlet mapped to "/"
Context context = tomcat.addContext("", baseDir.getAbsolutePath());
Tomcat.addServlet(context, "dispatcher", new DispatcherServlet(spring))
.setLoadOnStartup(1); // refreshes the Spring context
context.addServletMapping("/", "dispatcher");
// 4. Start, call it, stop
tomcat.start();
int port = tomcat.getConnector().getLocalPort();
System.out.println("Tomcat started, Spring context active: " + spring.isActive());
System.out.println("beans in the context: " + spring.getBeanDefinitionCount());
HttpResponse<String> r = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
URI.create("http://localhost:" + port + "/hello")).build(),
BodyHandlers.ofString());
System.out.println("GET /hello -> " + r.statusCode() + " " + r.body());
stop(tomcat);
FileSystemUtils.deleteRecursively(baseDir);
System.out.println("stopped, Spring context active: " + spring.isActive());
}
// Spring Boot configures logging for you; here Tomcat (java.util.logging) and
// Spring (through SLF4J and Logback) would otherwise log every step
static void quietLogging() {
LogManager.getLogManager().reset();
var logback = (LoggerContext) LoggerFactory.getILoggerFactory();
logback.getLogger("ROOT").setLevel(Level.WARN);
}
static void stop(Tomcat tomcat) throws LifecycleException {
tomcat.stop();
tomcat.destroy();
}
}
Tomcat started, Spring context active: true
beans in the context: 33
GET /hello -> 200 hello from a hand-built server
stopped, Spring context active: false
- The program had to create the Spring context, the Tomcat instance, a base directory for Tomcat's work files, a connector, a servlet context and the
, and map the servlet toDispatcherServlet . Spring Boot performs each of these steps in its server factory./ registered Spring MVC's infrastructure: the context held 33 bean definitions, counting the configuration class, the controller and Spring's internal processors. In a Spring Boot application,@EnableWebMvc provides the same beans with different defaults, such as the Jackson converter settings and static resource handling.WebMvcAutoConfiguration- The Spring context was refreshed by the
when Tomcat started it, because ofDispatcherServlet . In Spring Boot the order is reversed: the context starts first and creates the server.setLoadOnStartup(1) - Logging had to be quietened by hand. Tomcat logs through
and Spring through SLF4J; Spring Boot routes both into one logging system and appliesjava.util.logging .logging.level.*
What the program lacks shows the rest of Spring Boot's work: no server.*/error
Configuring the server with properties and customizers
Most server settings are a property away, and the rest are reachable from code through a customizer. The program enables response compression, lowers the header size limit and sets Tomcat's Server
package demo.settings;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.tomcat.servlet.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class ServerSettings {
// Code-level access to Tomcat, for settings that have no property
@Bean
WebServerFactoryCustomizer<TomcatServletWebServerFactory> tomcatCustomizer() {
return factory -> factory.addConnectorCustomizers(
connector -> connector.setProperty("server", "shop-api"));
}
@RestController
static class Endpoints {
@GetMapping("/small")
public String small() {
return "a short answer";
}
@GetMapping("/report")
public String report() {
return "line of a long report\n".repeat(500); // 11,000 characters
}
}
static void get(HttpClient http, String url, String... headers) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url));
if (headers.length > 0) {
request.headers(headers);
}
HttpResponse<byte[]> r = http.send(request.build(), BodyHandlers.ofByteArray());
System.out.println("GET " + url.substring(url.indexOf('/', 8))
+ (headers.length > 0 ? " (" + headers[0] + ": "
+ (headers[1].length() > 20 ? headers[1].length() + " chars" : headers[1])
+ ")" : ""));
System.out.println(" -> " + r.statusCode() + ", " + r.body().length + " bytes"
+ ", Content-Encoding: " + r.headers().firstValue("Content-Encoding").orElse("-")
+ ", Server: " + r.headers().firstValue("Server").orElse("-"));
}
public static void main(String[] args) throws Exception {
try (var context = new SpringApplicationBuilder(ServerSettings.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=WARN",
"server.compression.enabled=true",
"server.max-http-request-header-size=4KB")
.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String base = "http://localhost:" + port;
HttpClient http = HttpClient.newHttpClient();
get(http, base + "/report");
get(http, base + "/report", "Accept-Encoding", "gzip");
get(http, base + "/small", "Accept-Encoding", "gzip");
get(http, base + "/small", "X-Large-Header", "x".repeat(5000));
}
}
}
GET /report
-> 200, 11000 bytes, Content-Encoding: -, Server: shop-api
GET /report (Accept-Encoding: gzip)
-> 200, 86 bytes, Content-Encoding: gzip, Server: shop-api
GET /small (Accept-Encoding: gzip)
-> 200, 14 bytes, Content-Encoding: -, Server: shop-api
GET /small (X-Large-Header: 5000 chars)
-> 400, 435 bytes, Content-Encoding: -, Server: shop-api
- Without
, the 11,000-byte report was sent as it is. WithAccept-Encoding , it arrived as 86 bytes withAccept-Encoding: gzip . The report repeats one line 500 times, which compresses far better than typical data.Content-Encoding: gzip - The 14-byte answer was not compressed even though the client accepted gzip, because it is below
, 2KB by default. Compressing tiny responses costs more than it saves.server.compression.min-response-size - A request with a 5,000-character header broke
, and Tomcat rejected it with 400 before Spring saw it. The default is 8KB; large cookies or tokens are the usual reason to raise it.server.max-http-request-header-size=4KB - Every response carried
, set by theServer: shop-api . Your customizers run after Spring Boot's own by default, so code wins over properties when both set the same thing.WebServerFactoryCustomizer
| Property | Default | Effect |
|---|---|---|
server.port | 8080 | Port to listen on; 0 picks a free one |
server.address | All interfaces | Network address to bind to |
server.servlet.context-path | None | Prefix for every URL, such as /shop |
server.compression.enabled | false | Gzip for text, JSON and XML responses |
server.http2.enabled | false | HTTP/2, which also needs TLS for browsers |
server.max-http-request-header-size | 8KB | Largest request header block |
server.tomcat.threads.max | 200 | Worker threads; ignored with virtual threads |
server.tomcat.max-connections | 8192 | Open connections Tomcat will hold |
server.tomcat.accept-count | 100 | Queue for connections beyond that |
server.shutdown | graceful | Whether in-flight requests may finish on shutdown |
Virtual threads
Tomcat normally serves each request on a thread from a pool of platform threads, 200 by default. With Java 21's virtual threads, each request can get its own cheap thread instead, so requests that wait for a database or a remote service no longer use up the pool. The program asks the handler thread what it is, with the setting off and on:
package demo.threads;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse.BodyHandlers;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class VirtualThreads {
@RestController
static class WhoAmI {
@GetMapping("/thread")
public String thread() {
Thread t = Thread.currentThread();
String name = t.getName().replaceAll("\\d+", "N"); // numbers vary per run
return "virtual=" + t.isVirtual() + ", name pattern=" + name;
}
}
static void run(boolean virtual) throws Exception {
try (var context = new SpringApplicationBuilder(VirtualThreads.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=WARN",
"spring.threads.virtual.enabled=" + virtual)
.run()) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String body = HttpClient.newHttpClient().send(HttpRequest.newBuilder(
URI.create("http://localhost:" + port + "/thread")).build(),
BodyHandlers.ofString()).body();
System.out.println("spring.threads.virtual.enabled=" + virtual + " -> " + body);
}
}
public static void main(String[] args) throws Exception {
run(false);
run(true);
}
}
spring.threads.virtual.enabled=false -> virtual=false, name pattern=http-nio-auto-N-exec-N
spring.threads.virtual.enabled=true -> virtual=true, name pattern=tomcat-handler-N
- With the setting off, the request ran on a platform thread from Tomcat's pool, named
. Thehttp-nio-auto-N-exec-N part comes from the random port.auto - With
, the request ran on a virtual thread namedspring.threads.virtual.enabled=true . The controller code did not change.tomcat-handler-N
The same property also switches Spring's task executors and schedulers to virtual threads, and server.tomcat.threads.max
Graceful shutdown
When an application is stopped for a deployment, requests in progress should finish instead of failing halfway. The program starts a request that takes 1.5 seconds, closes the context while it runs, and tries a new request during the shutdown, once with each shutdown mode:
package demo.shutdown;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class GracefulShutdown {
static CountDownLatch requestStarted;
@RestController
static class SlowController {
@GetMapping("/slow")
public String slow() throws InterruptedException {
requestStarted.countDown();
Thread.sleep(1500); // an order that takes a while to save
return "order saved";
}
}
static String describe(CompletableFuture<HttpResponse<String>> call) {
try {
HttpResponse<String> r = call.join();
return r.statusCode() + " " + r.body();
} catch (RuntimeException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
return "failed: " + cause.getClass().getSimpleName();
}
}
static void run(String mode) throws Exception {
System.out.println("=== server.shutdown=" + mode);
requestStarted = new CountDownLatch(1);
var context = new SpringApplicationBuilder(GracefulShutdown.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=OFF", "server.shutdown=" + mode)
.run();
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build();
HttpRequest slow = HttpRequest.newBuilder(
URI.create("http://localhost:" + port + "/slow")).build();
var inFlight = http.sendAsync(slow, BodyHandlers.ofString());
requestStarted.await();
System.out.println("request in progress, closing the context");
var closing = CompletableFuture.runAsync(context::close);
Thread.sleep(300); // the shutdown has begun
var late = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(1)).build()
.sendAsync(slow, BodyHandlers.ofString());
System.out.println("in-flight request: " + describe(inFlight));
System.out.println("new request : " + describe(late));
closing.join();
System.out.println("context closed");
}
public static void main(String[] args) throws Exception {
run("graceful");
run("immediate");
}
}
=== server.shutdown=graceful
request in progress, closing the context
in-flight request: 200 order saved
new request : failed: ConnectException
context closed
=== server.shutdown=immediate
request in progress, closing the context
in-flight request: failed: IOException
new request : failed: ConnectException
context closed
- With
, the in-flight request completed withgraceful . Tomcat stopped accepting new connections at once, so the new request failed with200 order saved , and the context closed only after the slow request had finished.ConnectException - With
, Tomcat closed the connection under the running request, and the client got animmediate instead of a response. In a real application, the order might have been saved without the client ever hearing about it.IOException
Graceful shutdown has been the default since Spring Boot 3.4. It waits at most spring.lifecycle.timeout-per-shutdown-phaseREFUSING_TRAFFIC
Switching to Jetty
Spring Boot picks the server from the classpath. To use Jetty, exclude Tomcat from the web starter and add the Jetty starter:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</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>
The exclusion matters. When this page's programs were first run with both servers on the classpath, every one of them started Jetty: the startup program reported JettyServletWebServerWebServer
package demo.jetty;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.jetty.JettyWebServer;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class JettyServer {
@RestController
static class Endpoints {
@GetMapping("/small")
public String small() {
return "a short answer from " + Thread.currentThread().getName()
.replaceAll("\\d+", "N");
}
@GetMapping("/report")
public String report() {
return "line of a long report\n".repeat(500); // 11,000 characters
}
}
static void get(HttpClient http, String url, String... headers) throws Exception {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url));
if (headers.length > 0) {
request.headers(headers);
}
HttpResponse<byte[]> r = http.send(request.build(), BodyHandlers.ofByteArray());
System.out.println("GET " + url.substring(url.indexOf('/', 8))
+ (headers.length > 0 ? " (" + headers[0] + ": "
+ (headers[1].length() > 20 ? headers[1].length() + " chars" : headers[1])
+ ")" : ""));
String body = r.body().length < 60 ? ", body: " + new String(r.body()) : "";
System.out.println(" -> " + r.statusCode() + ", " + r.body().length + " bytes"
+ ", Content-Encoding: " + r.headers().firstValue("Content-Encoding").orElse("-")
+ ", Server: " + r.headers().firstValue("Server").orElse("-") + body);
}
public static void main(String[] args) throws Exception {
try (var context = new SpringApplicationBuilder(JettyServer.class)
.properties("server.port=0", "spring.main.banner-mode=off",
"logging.level.root=WARN",
"server.compression.enabled=true",
"server.max-http-request-header-size=4KB",
"server.jetty.threads.max=50")
.run(args)) {
WebServer webServer = ((WebServerApplicationContext) context).getWebServer();
Server jetty = ((JettyWebServer) webServer).getServer();
QueuedThreadPool pool = (QueuedThreadPool) jetty.getThreadPool();
System.out.println("WebServer: " + webServer.getClass().getSimpleName()
+ ", Jetty " + Server.getVersion());
System.out.println("Thread pool: " + pool.getClass().getSimpleName()
+ ", min " + pool.getMinThreads() + ", max " + pool.getMaxThreads());
String base = "http://localhost:" + webServer.getPort();
HttpClient http = HttpClient.newHttpClient();
get(http, base + "/report");
get(http, base + "/report", "Accept-Encoding", "gzip");
get(http, base + "/small", "Accept-Encoding", "gzip");
get(http, base + "/small", "X-Large-Header", "x".repeat(5000));
}
}
}
WebServer: JettyServletWebServer, Jetty 12.1.14
Thread pool: QueuedThreadPool, min 8, max 50
GET /report
-> 200, 11000 bytes, Content-Encoding: -, Server: -
GET /report (Accept-Encoding: gzip)
-> 200, 86 bytes, Content-Encoding: gzip, Server: -
GET /small (Accept-Encoding: gzip)
-> 200, 26 bytes, Content-Encoding: -, Server: -, body: a short answer from qtpN-N
GET /small (X-Large-Header: 5000 chars)
-> 431, 392 bytes, Content-Encoding: -, Server: -
- The web server was
, running Jetty 12.1.14.JettyServletWebServer gives the JettygetServer() , the counterpart of reaching Tomcat through a customizer.Server - Jetty uses a
.QueuedThreadPool set its maximum, and the minimum stayed at Spring Boot's default of 8. Requests ran on threads namedserver.jetty.threads.max=50 , notqtpN-N .http-nio-...-exec-N worked unchanged: the 11,000-byte report came back as 86 bytes of gzip when the client asked for it, and the short answer was not compressed.server.compression.enabled- The 5,000-character header, over the 4 KB limit from
, was rejected with 431 Request Header Fields Too Large. Tomcat answered the same request with 400, so clients and tests that check the exact status see a difference.server.max-http-request-header-size - No
header was sent. The Tomcat customizer that setServer applies toshop-api only; on Jetty, the same thing needs aTomcatServletWebServerFactory , or the portableWebServerFactoryCustomizer<JettyServletWebServerFactory> property.server.server-header
The common server.*spring.threads.virtual.enabledjetty-Nserver.tomcat.*server.jetty.*
Choosing server settings
| Need | Use |
|---|---|
| Run the server on a free port in tests | server.port=0WebServerApplicationContext |
| Code that runs once the application can serve requests | A listener for ApplicationReadyEvent |
| A setting with no property | A WebServerFactoryCustomizer |
| Smaller text and JSON responses | server.compression.enabled=true |
| Many requests waiting on I/O | spring.threads.virtual.enabled=true |
| Deployments without failed requests | Graceful shutdown, the default, with a suitable timeout |
| A different server | Jetty instead of Tomcat; Undertow is gone in Boot 4 |
| No server at all, such as a batch job | spring.main.web-application-type=none |
For what runs inside the server once it is up, see