The embedded server

spring_boot_starter_web runs an HTTP server inside the application. It starts when the context is ready and stops when the context closes. You configure it with server.* properties.

Why

You do not write HttpServer.bind or a request loop. The starter does it for you, in the same way as Spring Boot runs Tomcat for you:

The default server is dart:io's HttpServer. It runs on the Dart VM, in a compiled executable, and in a Flutter app on Android, iOS, macOS, Windows and Linux. It speaks HTTP/1.1 (with TLS if you want). It does not speak HTTP/2.

Example

# lib/resources/application.yml
server:
  port: 8080
  address: 0.0.0.0
  context-path: /shop
  max-http-request-body-size: 20MB
  mime-mappings:
    wasm: application/wasm
spring:
  main:
    register-shutdown-hook: true   # Ctrl+C and SIGTERM stop the server gracefully
  mvc:
    log-request-details: false
// bin/main.dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

import 'spring_gen/main.spring.dart';

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
dart run build_runner build
dart run bin/main.dart
# INFO  Web server started on port 8080 (http)

With this configuration, @GetMapping('/books') answers GET http://host:8080/shop/books.

Properties

Key Type Default Meaning
server.port int 8080 The port to listen on. 0 picks a free port.
server.address String all interfaces; 127.0.0.1 in Flutter apps The address to listen on: an IP address or a host name.
server.context-path String none A prefix of every path, such as /shop.
server.max-http-request-body-size DataSize 10MB The largest request body. Larger is a 413. -1: no limit.
server.mime-mappings.<ext> Map<String, String> empty More media types for static files, by file extension.
spring.main.web-application-type String not set none starts no server.
spring.test.web-environment String not set Set by tests: which test environments start a server.
spring.mvc.log-request-details bool false Show parameter and header values in the request logs.
local.server.port int written by the server The port the server really listens on. Read it; do not set it.

The other server.* keys have their own pages: TLS, compression, timeouts, overload, the pool of isolates and its scaling, reverse proxy, shutdown, WebSocket and sessions. The full list is on All properties.

server.port

Web server failed to start. Port 8080 was already in use.

Action: Identify and stop the process that is listening on port 8080, or
configure this application to listen on another port (server.port; 0 picks a free one).

The port is in use also when the same process already listens on it.

A port computed in code goes through a WebServerFactoryCustomizer (see "Changing the server in code" below).

local.server.port

@Component()
@Log()
class StartupUrl {
  @EventListener()
  void onServer(WebServerInitializedEvent event) =>
      log.info('Open http://localhost:${event.port}/');
}

Setting local.server.port yourself does nothing: nothing reads it to choose the port.

server.address

server.context-path

server.max-http-request-body-size

import 'dart:io' show File;

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

@RestController()
class ImageController {
  // Disk images up to 4 GB, written to a file as they arrive.
  @PutMapping('/images/{name}')
  @ResponseStatus(HttpStatus.noContent)
  Future<void> upload(ServerHttpRequest request, @PathVariable() String name) async {
    request.attributes[maxRequestBodySizeAttribute] = 4 << 30;
    await request.body.pipe(File('/srv/images/$name').openWrite());
  }
}

server.mime-mappings.*

server:
  mime-mappings:
    wasm: application/wasm
    webmanifest: application/manifest+json
server.mime-mappings.wasm=application/wasm
server.mime-mappings.webmanifest=application/manifest+json

A file whose type is unknown is sent as application/octet-stream. See Static resources.

spring.main.web-application-type

spring.test.web-environment

Value Server Port
mock none; MockMvc calls the dispatcher in memory —
random-port a real server 0, a free port, whatever server.port says
defined-port a real server server.port
none none —

Any other value starts no server either. See Testing.

spring.mvc.log-request-details

logging.level.spring.web.servlet.DispatcherServlet=trace
spring.mvc.log-request-details=true
DEBUG GET "/api/books", parameters={q=[dune], page=[2]}, headers={host: localhost:8080, authorization: masked}
DEBUG Completed 200 OK

Without log-request-details, the same request logs parameters={masked} and headers={masked}.

The startup log line

When the server listens, the starter logs at info level, under the logger spring.web.server:

Web server started on port 8080 (http)

The port is the real one (useful with server.port=0). The scheme is https when server.ssl.certificate is set and server.ssl.enabled is not false. When the server stops, it logs Web server stopped.

Other loggers of the starter:

Logger What
spring.web.server start, stop, graceful shutdown, server errors, WebSocket sessions dropped
spring.web.servlet.DispatcherServlet one line per request and its result (debug)
spring.web.mvc the mappings found at startup (debug: their count; trace: each one), errors written
spring.web.forwarded forwarded headers applied or ignored (debug)
spring.web.session sessions
spring.web.multipart uploads

The server's lifecycle

  1. The context starts. The webServerStartStopLifecycle bean is a SmartLifecycle with phase SmartLifecycle.defaultPhase - 2048, as in Spring Boot. It starts before the lifecycle beans of the default phase and stops after them.
  2. Should a server run? Not when spring.main.web-application-type=none. In a test, only for random-port and defined-port.
  3. The server is created. The webServerFactory bean is asked for a server, with the dispatcherHandler as its handler.
  4. The socket is bound. dart:io binds asynchronously. SpringApplication waits for it before it publishes ApplicationStartedEvent, runs the runners and publishes ApplicationReadyEvent. So when your ApplicationRunner runs, the server already listens.
  5. The port is published. local.server.port is set, the startup line is logged, and a WebServerInitializedEvent is published.
  6. The context closes. The server stops as server.shutdown says. See Shutdown.

To wait for the server in code (for example in a test without the test starter):

final lifecycle = context.getBean<WebServerStartStopLifecycle>();
final server = await lifecycle.started;          // null when no server runs
final uri = Uri.parse('http://localhost:${server!.port}/api/books');

A failure to start other than a port in use (an address that cannot be bound, a certificate that cannot be read) also fails the start. In a context started without SpringApplication, the failure is logged as Web server failed to start and the context closes.

Stopping with Ctrl+C

spring.main.register-shutdown-hook is false by default here (Spring Boot: true), because listening for signals keeps a Dart program alive. Set it to true so that Ctrl+C (SIGINT) and SIGTERM close the context. Then the server stops gracefully and @PreDestroy methods run. Without it, the signal ends the process at once.

What the server answers by itself

Some requests never reach your filters or controllers. The server answers them with a ProblemDetail (application/problem+json):

Request Answer
A method the starter does not know 501 Not Implemented
With server.ssl.client-auth=need, no client certificate 403 Forbidden
HTTP/1.1 without Host, a malformed Host, or an absolute target whose host is not the Host header 400 Bad Request
An encoded /, \ or NUL in the path (%2F, %5C, %00) 400
A . or .. segment hidden behind ; (/files/..;x/secret) 400
A % escape that is not valid UTF-8 in the path or query (/%FF) 400

Other rules of the dart:io server:

Known limits of dart:io that matter behind a proxy:

Changing the server in code

Properties cover most needs. When a value is computed, declare a WebServerFactoryCustomizer bean. The starter calls each one once, on the default factory, after it applied server.*:

import 'dart:io' show Platform;

import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

// The hosting platform gives the port in the PORT variable.
@Component()
class PortCustomizer implements WebServerFactoryCustomizer {
  @override
  void customize(ConfigurableWebServerFactory factory) =>
      factory.settings = factory.settings.copyWith(
        port: int.parse(Platform.environment['PORT'] ?? '8080'),
      );
}

ServerProperties.copyWith keeps a value when its argument is null, so it cannot reset address, ssl or a timeout to "none". server.context-path and server.request-timeout are read by the dispatcher from the properties, so a customizer cannot change them.

To replace the server entirely, declare your own WebServerFactory bean. The default one backs off (@ConditionalOnMissingBean):

@Configuration()
class ServerConfig {
  @Bean()
  WebServerFactory webServerFactory() => MyServerFactory(); // returns a WebServer
}

A WebServer has start(), stop({Duration? timeout}) and port. Everything above the server works on ServerHttpRequest and ServerHttpResponse and never imports dart:io, so another server needs only these two classes. IoWebServerFactory and IoWebServer are in package:spring_boot_starter_web/io.dart, which you can import to wrap the default server or to start one outside the context:

import 'package:spring_boot_starter_web/io.dart';
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';

Future<void> main() async {
  final server = IoWebServerFactory(const ServerProperties(port: 0)).getWebServer(
    FunctionHttpHandler((request, response) => response.send(200, 'pong')),
  );
  await server.start();
  print('listening on ${server.port}');
}

Running in Flutter

The starter works in a Flutter app on Android, iOS, macOS, Windows and Linux. The server runs in the main isolate, with the same beans as the widgets: a local API, a companion server for other devices, a page served to a browser on the same machine.

spring_boot_starter_web has no web server on this platform: the web has no server sockets. Run the server on the VM or in a Flutter app on mobile or desktop, or set spring.main.web-application-type=none.

In Spring (Java)

@SpringBootApplication
public class ShopApplication {
  public static void main(String[] args) {
    SpringApplication.run(ShopApplication.class, args);
  }
}
server.port=8080
server.address=127.0.0.1
server.servlet.context-path=/shop

Differences that matter:

See also