spring_boot_dart
spring_boot_dart is the part of Spring for Dart that starts an application. It is the Dart port of Spring Boot's SpringApplication, its external configuration, its @ConfigurationProperties binding and its auto-configuration.
With spring_core_dart alone you have a container of beans, but you still write the start yourself: read the config files, create the context, set the log levels, run the start-up work. spring_boot_dart does all of it from one annotation on main.
Why
Every application needs the same start-up code, and it is easy to get wrong:
- configuration from files, environment variables, the command line and
--dart-define, with profiles such asdevandprod, and one clear rule for which source wins; - the beans of your package plus the beans of the libraries ("starters") you depend on, where your own bean always wins over a starter's;
- groups of settings bound into typed classes, converted and validated before any bean uses them;
- start-up tasks run in order, events at each step, a clean shutdown;
- a readable report when something cannot start, instead of a stack trace.
spring_boot_dart gives you all of this with Spring Boot's names and rules, so configuration and habits from a Spring project carry over. It works the same in a server, a command-line tool and a Flutter app, on the Dart VM, in AOT builds and on the web.
Setup
# pubspec.yaml
dependencies:
spring_boot_dart: ^0.9.0
dev_dependencies:
build_runner: ^2.17.0
spring_core_dart_generator: ^0.9.0 # required: it scans the package
spring_boot_dart exports spring_core_dart, so one import is enough. It depends on nothing else. Most applications do not add it directly: every starter (spring_boot_starter_web, spring_boot_starter_flutter, ...) depends on it and exports it.
Example
A complete application with typed settings, a start-up task and a profile.
// bin/main.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'spring_gen/main.spring.dart'; // written by build_runner
// Every key under shop.* in one typed, validated object.
@ConfigurationProperties('shop')
@Validated()
class ShopProperties {
@NotBlank()
String name = 'NEON Books';
Duration deliveryTime = const Duration(days: 3); // shop.delivery-time=2d
@Min(1)
int maxBasketSize = 10; // shop.max-basket-size
}
// Runs once the application has started.
@Component()
@Log()
class Greeting implements ApplicationRunner {
Greeting(this.shop);
final ShopProperties shop;
@override
void run(ApplicationArguments args) =>
log.info('${shop.name} is open, ${shop.maxBasketSize} books per basket');
}
@SpringBootApplication()
void main(List<String> args) => runApplication(args);
# lib/resources/application.yml
spring:
application:
name: neon-books
shop:
max-basket-size: 20
logging:
level:
root: info
# lib/resources/application-prod.yml: read only with the prod profile
shop:
max-basket-size: 50
Running it
dart run build_runner build # writes bin/spring_gen/main.spring.dart
dart run bin/main.dart # max-basket-size 20
dart run bin/main.dart --spring.profiles.active=prod # 50
SHOP_MAXBASKETSIZE=30 dart run bin/main.dart # 30: the environment wins over the files
The start logs, at INFO:
Starting neon-books using Dart 3.13.5 with PID 4242
No active profile set, falling back to 1 default profile: "default"
Started neon-books in 0.07 seconds
NEON Books is open, 20 books per basket
With shop.max-basket-size=0 the application does not start. It prints a report that names the key:
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target properties under 'shop' failed:
- shop.max-basket-size: must be greater than or equal to 1 (was "0")
Action:
Update the application's configuration (lib/resources/application.properties, command line or environment).
How it works
Dart has no reflection at run time, so the scan happens at build time. dart run build_runner build reads the whole package (lib/ and the directory of main; there is no @ComponentScan to write) and generates spring_gen/main.spring.dart with:
- the bean definitions of the package;
- the files of
lib/resources/, embedded so they work in every build; - the auto-configuration modules of every dependency;
- the
springApplicationgetter and therunApplicationandrunApplicationAsyncfunctions;reloadApplicationandreloadApplicationAsyncare inmain.spring.debug.dart, for debug and profile builds only.
runApplication(args) then does what Spring Boot's SpringApplication.run does. The steps are on SpringApplication.
What is inside
Starting:
- SpringApplication: the steps of a start, the constructor,
runandrunAsync, the banner, lazy start. - Runners:
ApplicationRunner,CommandLineRunnerandApplicationArguments. - Events: the start-up events and the application's availability.
- Shutdown and exit codes: the shutdown hook, the shutdown timeout,
SpringApplication.exit. - Failure reports:
APPLICATION FAILED TO START,FailureAnalyzerand the condition report. - Hot reload: Flutter and Dart VM reloads that restart the context when the beans change.
External configuration:
- Overview: every source, and which one wins.
- Config files: YAML and
.properties, documents, the search locations. - Profiles: activation, groups, profile files,
on-profiledocuments, cloud platforms. - Imports:
spring.config.importand every kind of location: files, directories, config trees, HTTP, packages, assets. - Command line, environment and --dart-define: the other sources, relaxed names,
SPRING_APPLICATION_JSON, placeholders. - @ConfigurationProperties: typed settings, binding, conversion and validation.
Auto-configuration:
- Auto-configuration and starters: how starters add beans, their order, exclusion, modules left out of the build, writing a starter.
- Conditions: every
@ConditionalOn...annotation. - Built-in beans: the
ObjectMapper, the validator, the message source, the lifecycle processor and the availability bean. - Logging levels:
logging.level.*andlogging.group.*,--debugand--trace. - Versions and compatibility: the release train and the
requirescheck.
Reference:
- All properties: every key
spring_boot_dartreads. - Differences from Spring: what works differently than in Spring Boot.
In Spring (Java)
@SpringBootApplication
public class NeonBooks {
public static void main(String[] args) {
SpringApplication.run(NeonBooks.class, args);
}
}
Differences that matter:
@SpringBootApplication()goes on themainfunction, not on a class, and the package is scanned at build time. Runbuild_runnerafter you change annotations or add a starter.lib/resources/plays the role of the classpath. Locations are writtenresources:, notclasspath:.- The shutdown hook is off by default (
spring.main.register-shutdown-hook=trueturns it on), because a Dart program that listens for signals never ends by itself. - A few property prefixes are renamed (
spring.jackson.*isspring.json.*), and the old name stops the start. - The full list is on Differences from Spring.