Differences from Spring
spring_boot_starter_web follows Spring Boot and Spring MVC: the same annotations, the same property names where they make sense, the same answers. This page lists every place where it does not, and why, grouped by topic. The last section lists what is not there yet.
Why
When you port a Spring application, or follow a Spring tutorial, you need to know where the behaviour is not the one you expect. Most differences come from three facts:
- Dart is not Java. There is no reflection at run time and no servlet container. Annotations on exception classes cannot be read at run time, and one
Typecannot be tested for being a subtype of another. - The server is
dart:io'sHttpServer, not Tomcat. Some rules come from it. - Some defaults are safer. A few limits exist here that Spring leaves to the container or to the application.
Example
The same controller in both. The code is nearly the same; the differences are in the details below.
@RestController()
@RequestMapping('/api/books')
class BookController {
BookController(this.books);
final BookService books;
@GetMapping('/{isbn}')
Future<Book> find(@PathVariable() String isbn) => books.find(isbn);
@GetMapping()
Future<List<Book>> search(@RequestParam('q') String? query) => books.search(query);
}
@RestController
@RequestMapping("/api/books")
class BookController {
@GetMapping("/{isbn}")
Book find(@PathVariable String isbn) { ... }
@GetMapping
List<Book> search(@RequestParam(name = "q", required = false) String query) { ... }
}
Required or optional comes from the Dart parameter (String?, a default value), not from required and defaultValue. See @RequestParam.
Configuration
- Renamed properties.
server.servlet.context-pathisserver.context-path,server.servlet.session.*isserver.session.*, andspring.servlet.multipart.*isspring.web.multipart.*: there is no servlet container. Any key under an old prefix, in any source (a file, the command line, an environment variable), stops the start and names the new key. Spring's properties migrator only logs a warning. - This starter's own keys, not in Spring Boot:
server.max-http-request-body-size,server.request-timeout,server.max-concurrent-requests,server.max-connections,server.retry-after,server.isolates.*,spring.web.debug.*,server.forward-headers.trusted-proxies,server.websocket.*,spring.mvc.sse.heartbeat-interval,spring.web.multipart.max-part-count(Spring Boot:server.tomcat.max-part-count),spring.web.resources.spa-fallback,spring.web.resources.directory-index. server.connection-timeoutis the key Spring Boot 2.0 had. Spring Boot 3 and 4 useserver.tomcat.connection-timeout.spring.main.register-shutdown-hookisfalseby default (a key ofspring_boot_dart), because listening for signals keeps a Dart program alive. Set it totrue, orCtrl+Cand SIGTERM end the process without a graceful shutdown.spring.main.web-application-typeonly knowsnone. There is one kind of server, notservletandreactive.- No
@EnableWebMvc. Every@RestControllerin the scanned package is mapped.
See All properties.
The server
dart:io'sHttpServer, not Tomcat. HTTP/1.1 only;server.http2.enabledis not read. Noserver.tomcat.*keys.- TLS from PEM file paths. No key stores, no SSL bundles, no
classpath:orresources:locations. Withserver.ssl.client-auth=need, a client without a certificate completes the TLS handshake and gets a 403 per request. See TLS. server.request-timeoutandRequestDeadlineare extensions. Spring times out connections (Tomcat) and asynchronous requests (spring.mvc.async.request-timeout), not the handling of a synchronous request, and no deadline follows a request into the calls it makes. See Timeouts.- Stalled request bodies get a 408 after
server.connection-timeout(60 s). With Tomcat the read fails and Spring answers 400. - No connection limit unless set.
server.max-connectionsandserver.max-concurrent-requestsset one (Tomcat'smax-connectionsis 8192 by default). Past either a request is answered 503 withRetry-Afterat once, instead of waiting. See Overload. - Isolates, not threads. Tomcat's worker threads share the beans. Here the server answers from one isolate;
server.isolates.countadds isolates that each run the whole application with their own beans, so sessions, caches and counters in memory are per isolate. See A pool of isolates. - A body over
server.max-http-request-body-size(10 MB) is a 413, whatever its type. Tomcat has no such limit for every body. - Two
Hostheaders and a%without two hex digits are accepted (dart:iokeeps the lastHost;/a%G1is read as/a%25G1), where Tomcat answers 400. - A raw
\in the request target is a/.dart:ioparses the target before the server sees it and keeps no raw form, so/files/..\..\secretarrives as/secret(its..resolved), and raw bytes past ASCII are read as Latin-1 (/cafésent as UTF-8 arrives as/caf%C3%83%C2%A9). Tomcat answers 400 to both. Filters, security rules and controllers all see the same path, but a proxy in front whose rules look at paths must refuse\itself. Content-LengthwithTransfer-Encodingis answered 400, and the connection closes, only when the server sees both headers (Tomcat always answers 400).dart:ioshows both only in some spellings (the length first and the encoding not written exactlychunked); in the others it drops theContent-Lengthitself and the request is read as chunked. Use a proxy that refuses such requests.- No
Serverheader, no defaultContent-Type.dart:io'sX-Frame-Options: SAMEORIGINandX-Content-Type-Options: nosniffare sent on every answer (Spring Boot without Spring Security sends neither). - Graceful shutdown closes open event streams and WebSocket sessions at once (1001), in both modes. See Shutdown.
- A Flutter app listens on
127.0.0.1by default. See The embedded server.
Behind a proxy
nativeandframeworkdo the same thing: both apply the forwarded headers of trusted proxies only, as Tomcat'sRemoteIpValve. Spring'sForwardedHeaderFilter(framework) believes every peer.- Trusted proxies are addresses and CIDR ranges (
server.forward-headers.trusted-proxies), not Tomcat's regular expression. X-Forwarded-PrefixandX-Forwarded-Sslare not read.
Controllers and parameters
- More startup checks than Spring: a path variable without a parameter, a parameter nothing can fill, an invalid
@ExceptionHandlerstop the start with the list of problems. See Startup checks. - Required or optional comes from the Dart parameter, not from
requiredanddefaultValue: a nullable parameter getsnull, an optional one keeps its Dart default. - No
@ModelAttribute, no binding of forms to objects. Form fields reach a handler through@RequestParam(one field, a list, or all of them as aMap) or a@RequestBody() Map<String, String>. - No
HttpSessionparameter. A handler gets the session withrequest.getSession(). See Sessions. - Custom argument resolvers are asked before the built-in ones (Spring asks them after), so a starter can take over any parameter, as the security starter's
@AuthenticationPrincipaldoes. See WebMvcConfigurer. @ResponseStatusgoes on handler methods or the controller class, not on exception classes, whose annotations cannot be read at run time. Throw aResponseStatusExceptionor implementErrorResponseinstead.
Errors
- Errors are
ProblemDetails (application/problem+json), always. Spring Boot's default is the/errorJSON (timestamp,status,error,path) unlessspring.mvc.problemdetails.enabled=true. Here there is no/errorendpoint, noErrorController, andserver.error.*is not read. The exceptions are the plain-text answers Spring gives too: a refused CORS request or WebSocket handshake. @ExceptionHandler([types])matches exact run-time types, because Dart cannot test whether aTypeis a subtype of another. Subtypes match through the type of the exception parameter:@ExceptionHandler() void on(StateError e). See @ExceptionHandler.@ControllerAdvice.of(basePackages: ...)takes library URI prefixes (package:shop/admin/) instead of Java packages, andannotationsmatch a controller's annotation by its exact type. There is nobasePackageClasses. See @ControllerAdvice.- A
HandlerExceptionResolverreturns anErrorResponse(ornull) instead of writing into the response and returning aModelAndView. The built-in resolution (the@ExceptionHandlermethods,ResponseStatusException) comes first; resolver beans are asked after it. See HandlerExceptionResolver.
Streams, uploads and downloads
- A declared
Stream<Uint8List>orStream<List<int>>result is raw bytes. Spring MVC has no byte stream result; Spring WebFlux writes aFlux<DataBuffer>the same way. Other streams are server-sent events (or NDJSON). See Downloads. - Event streams start with a
:comment line, becausedart:iosends the headers with the first body bytes. Clients ignore it. See Server-sent events. - An
SseEmitterwithout a timeout never times out whenspring.mvc.async.request-timeoutis not set: there is no servlet container whose default applies (Tomcat's 30 seconds in Spring). It ends when it is completed, when the client goes away, or when the server stops.spring.mvc.async.request-timeoutapplies toSseEmitters only. - Multipart without a servlet container. The
spring.web.multipart.*keys are Spring Boot'sspring.servlet.multipart.*without the servlet, and the temporary files are this starter's own:file-size-thresholdis0B, so every file goes to disk. Onlymultipart/form-dataparts are bound to@RequestPart, notmultipart/mixed. See Uploads. - One byte range per request. Several ranges get the whole content, not
multipart/byteranges. AResourcea controller returns has noETag(the static resources have one).
Static resources
Stricter and a little richer than Spring's ResourceHttpRequestHandler. See Static resources.
- Dot files are not served (Spring serves them);
.well-known/is. ;and empty segments in the path are a 404. Spring Security's firewall answers them with a 400; plain Spring MVC serves them.- A symbolic link that leaves the location is refused, and so is a path that only Windows would read as another file.
- They send a weak
ETag(Spring sends none unless anetagGeneratoris set),X-Content-Type-Options: nosniff(Spring Security adds it in Spring),Cache-Controlon a304too, andapplication/jsonforapple-app-site-association. - A path without a file gets the dispatcher's 404 (
No endpoint GET /x.), where Spring 6.1 answersNo static resource x.. HandlerInterceptors do not run for them: they are for controller methods.spring.web.resources.spa-fallbackanddirectory-indexare this starter's own keys.- Not supported:
spring.web.resources.chain.enabled,chain.cache, the version strategies, the webjars mapping. - A precompressed variant is a
ResourceHandlerRegistrationsetting (setCompressed, orspring.web.resources.chain.compressed), instead of Spring'sresourceChain(true).addResolver(new EncodedResourceResolver()). - Locations are
resources:andfile:.resources:is a folder oflib/resources/, not its root (which holds the configuration). Another prefix stops the start.META-INF/resources/andresources/are not in the defaults, as Dart has no jars.
Sessions
- The session cookie is
SameSite=Laxby default. - The number of sessions is limited (
server.session.max-sessions, 10000). At the limit, expired sessions are removed, then a new session is refused with a 503. - Sessions live in memory of one process, unless you declare another
HttpSessionRepositorybean.
See Sessions.
CORS
- A pre-flight that several handlers match (with
@CrossOrigineach; no handler of exactly that path, or several) gets the first one's CORS rules. Spring allows it from any origin with credentials, whatever the handlers' specificity. - CORS values outside visible US-ASCII are refused with a 403: an
Origin, or a pre-flight's requested method or headers, with a space, a control character or a letter beyond ASCII, even where*allows any. Spring echoes such a method or header (no browser sends one), and refuses such anOrigintoo. - An
Originlonger than 1024 characters is never allowed (CORS and WebSocket handshakes: a 403), whatever the rules,*included. A real origin is under 300 characters. Spring checks any length, and its patterns' regular expressions slow down with it. spring.web.cors.*is not read. CORS is configured with@CrossOrigin,WebMvcConfigurer.addCorsMappingsor acorsConfigurationSourcebean.
See CORS.
WebSocket
- The message limits are properties of this starter (
server.websocket.max-text-message-sizeandmax-binary-message-size, 8 KB each, Tomcat's defaults). Spring sets them on the container (ServletServerContainerFactoryBean). The text limit counts UTF-8 bytes; Tomcat counts characters. - No permessage-deflate. Tomcat negotiates it.
- Every session has send limits (
server.websocket.send-buffer-size-limit, 512 KB, andsend-time-limit, 10 s; past them the connection is dropped with 4500), the defaults of Spring'sConcurrentWebSocketSessionDecorator. In Spring they apply to STOMP sessions and to sessions you decorate; a plain handler on Tomcat blocks the sending thread instead (up to Tomcat's 20-second blocking send timeout). AwaitIoWebSocketSession.flush()aftersendMessageto wait the same way.
See WebSocket.
Testing
MockMvctakes named expectations (andExpect(status: 200, json: ...), matchers allowed) instead ofstatus().isOk()andjsonPath(...).ApplicationContextRunnerstarts no server unless the test setsspring.test.web-environment=random-port.
See Testing.
Not yet
These are planned but not there yet:
@ConditionalOnWebApplicationand test slices such as@WebMvcTest.ResponseBodyEmitter. AStream<T>result covers server-sent events and NDJSON.- Several byte ranges as
multipart/byteranges, anETagfor aResourcea controller returns, and@RequestPartwithmultipart/mixed. spring.web.cors.*andserver.max-http-request-header-size.- A per-route request timeout.
server.request-timeoutapplies to every request. - Flutter: a warning when a handler blocks the main isolate, decoding big JSON bodies in another isolate, and the whole server in a background isolate.
- Other servers (for example on
shelf) behind the sameWebServerFactory, and STOMP over WebSocket.
In Spring (Java)
This whole page compares with Spring. In short, code moves over with small changes:
- annotations keep their names (
@RestController,@GetMapping,@PathVariable,@RequestBody,@ExceptionHandler,@ControllerAdvice,@CrossOrigin); required = falsebecomes a nullable parameter,defaultValuea Dart default;server.servlet.*andspring.servlet.multipart.*loseservlet;- error bodies are
ProblemDetails; @ResponseStatuson exception classes becomes aResponseStatusExceptionor anErrorResponse.