The application: @SpringBootApplication
@SpringBootApplication() on main (from spring_boot_dart) is the one annotation an application needs. For the library that declares it, the generator writes a .spring.dart file with everything needed to start the application:
- a module with every bean of the package;
springApplication: the beans, the auto-configuration of every starter in your dependencies, the files oflib/resources/and the--dart-definekeys;runApplication,runApplicationAsyncand the hot reload functions.
// bin/main.dart
import 'package:spring_boot_starter_web/spring_boot_starter_web.dart';
import 'spring_gen/main.spring.dart'; // written by the generator
@SpringBootApplication()
void main(List<String> args) => runApplication(args);
dart run build_runner build writes bin/spring_gen/main.spring.dart. For a Flutter app, main is in lib/main.dart and the file is lib/spring_gen/main.spring.dart.
Why
In Spring Boot, @SpringBootApplication on the main class turns on component scanning from the class's package, and auto-configuration from every starter on the classpath. SpringApplication.run then finds both at startup.
Dart cannot find either at run time: there is no classpath to search and no META-INF/spring/...AutoConfiguration.imports to read. So the generator does both searches at build time and writes the result as one value, springApplication, that main only has to run. Nothing else is needed: no @ComponentScan, no list of modules, no registration of starters. Adding a starter to pubspec.yaml and running build_runner is enough.
What is scanned
The scan covers the whole package:
Where main is |
Scanned directories |
|---|---|
bin/main.dart |
lib/ and bin/ |
lib/main.dart (Flutter) |
lib/ |
test/app/main.dart |
lib/ and test/app/ |
example/main.dart, example/shop/bin/main.dart |
only example/ |
The doc comment of the generated $application getter names them: "Beans found by @ComponentScan in lib/ and bin/."
An entry point under example/ is the example of a library or a starter. Only example/ is scanned, and the package's own auto-configuration is added like any other dependency's: the package's lib/ reaches the example the same way it reaches any application that depends on it.
Every .dart file below those directories is scanned, sorted by path, generated files excluded. The beans go into one module named application, declared as the getter $application.
Nested @ComponentScan roots
A @ComponentScan file inside the scanned directories owns its directory. Its beans stay in its own module, and $application imports that module instead (only the outermost scans; see nested scans). The server guide of the repository has all its beans under lib/src/, behind one scan root, so its application module is empty and only imports it:
// lib/src/app.dart
@ComponentScan()
final BeanModule appBeans = $appBeans;
// bin/spring_gen/main.spring.dart (excerpt, prefixes kept)
/// Beans found by `@ComponentScan` in `lib/ and bin/`.
_i1.BeanModule get $application => _i1.BeanModule(
r'application',
[],
imports: [_i2.appBeans],
resources: const { /* the files of lib/resources/ */ },
);
The generated file
The file holds, in this order: the generated classes (AOP proxies and other subclasses), $application, springApplication, the four run and reload functions, and then the @Log and Flutter extensions.
springApplication
An excerpt of bin/spring_gen/main.spring.dart of the server guide, an application with the web, security, WebSocket, Feign, cache and scheduling starters (153 --dart-define entries shortened to two):
/// The `@SpringBootApplication` of the current code (a getter, so it is
/// up to date after a hot reload).
_i3.SpringApplication get springApplication => _i3.SpringApplication(
[$application],
autoConfigurations: [
_i4.springBootAutoConfiguration,
_i5.springBootStarterCacheAutoConfiguration,
_i6.springBootStarterFeignAutoConfiguration,
_i7.springBootStarterLoggingAutoConfiguration,
_i8.springBootStarterOauth2ClientAutoConfiguration,
_i9.springBootStarterSchedulingAutoConfiguration,
_i10.springBootStarterSecurityAutoConfiguration,
_i10.springBootStarterSecurityOAuth2ClientAutoConfiguration,
_i11.springBootStarterWebAutoConfiguration,
_i12.springBootStarterWebsocketAutoConfiguration,
_i13.springSecurityCoreAutoConfiguration,
],
autoConfigurationMetadata: {
_i10.springBootStarterSecurityAutoConfiguration:
const _i3.AutoConfigurationModule(
after: ['springBootStarterOauth2ClientAutoConfiguration'],
),
_i10.springBootStarterSecurityOAuth2ClientAutoConfiguration:
const _i3.AutoConfigurationModule(
before: ['springBootStarterOauth2ClientAutoConfiguration'],
),
},
dartDefines: {
if (const bool.hasEnvironment('DEBUG'))
'DEBUG': const String.fromEnvironment('DEBUG'),
if (const bool.hasEnvironment('LOGGING_FILE_NAME'))
'LOGGING_FILE_NAME': const String.fromEnvironment('LOGGING_FILE_NAME'),
// ...
},
fingerprint: !const bool.fromEnvironment('dart.vm.product')
? _$fingerprint
: null,
);
Its arguments:
| Argument | Written when | What it holds |
|---|---|---|
| first argument | always | [$application], the module of the package's beans. |
autoConfigurations |
a dependency has auto-configuration | The @AutoConfigurationModule variables of every dependency's lib/spring_auto_configuration.dart, sorted by package and then by name. See Auto-configurations. |
autoConfigurationMetadata |
a module sets order, before or after |
Those values, for each such module. The runtime sorts the modules with them. |
exclude, excludeName |
@SpringBootApplication sets them |
The auto-configurations to leave out (see below). |
dartDefines |
always in practice | One entry per property a --dart-define may set. See --dart-define keys. |
fingerprint |
debug and profile builds | A hash of the generated code, from the debug part, for hot reload; null in a release build (see below). |
springApplication is a getter, not a variable. After a hot reload replaces its body, the next call builds the application from the new code.
A module whose starter lets the application leave it out of the build, or out of a release build, is decided at build time from the application's application.properties or application.yml (see Modules left out of the build). A module kept only outside release builds is written behind a constant condition, so a release build compiles it away with everything only it uses:
// lib/spring_gen/main.spring.dart of the seo_site example (excerpt)
autoConfigurations: [
_i5.springBootAutoConfiguration,
_i6.springBootStarterFlutterAutoConfiguration,
if (!const bool.fromEnvironment('dart.vm.product'))
_i6.springBootStarterFlutterDebugAutoConfiguration,
_i7.springBootStarterFlutterNavigationAutoConfiguration,
_i8.springBootStarterLoggingAutoConfiguration,
],
Only the dependencies of the application count, direct or through other packages, read from the pubspec.yaml files. In a pub workspace the package config lists every member of the workspace, but an application does not get the auto-configuration of a sibling it does not depend on.
A starter can declare the spring_boot_dart versions it works with (requires). If the version in use is outside that range, the build fails with the starter, the range, the version and what to upgrade.
runApplication and runApplicationAsync
/// Starts the application: config files, environment, context, runners
/// (asynchronous runners go on one after another after it returns;
/// [runApplicationAsync] waits for them).
ConfigurableApplicationContext runApplication(List<String> args) =>
springApplication.run(args, hotReload: () => springApplication);
/// Like [runApplication], reading config files asynchronously (Flutter assets)
/// and completing once every runner has finished.
Future<ConfigurableApplicationContext> runApplicationAsync(
List<String> args,
) => springApplication.runAsync(args, hotReload: () => springApplication);
Call one of them from main. They pass hotReload: () => springApplication, so the runtime can rebuild the application from the current code after a hot reload.
A Flutter app hands the getter to its root widget instead:
// lib/main.dart
@SpringBootApplication()
void main() => runApp(SpringApplicationWidget(application: () => springApplication));
Other entry points of the same package can import the generated file and use these functions too, without an annotation of their own. The server guide's bin/advanced.dart imports spring_gen/main.spring.dart and calls runApplicationAsync([...]) with other arguments.
Hot reload
What only a hot reload uses is in a part of its own, lib/spring_gen/main.spring.debug.dart, which the library refers to only under !const bool.fromEnvironment('dart.vm.product'). A release build (dart compile exe, AOT, a Flutter release) compiles none of it; a debug or profile run behaves as before, hot reload included.
// lib/spring_gen/main.spring.debug.dart (generated)
const _$fingerprint = '3ada566f';
/// For hot reload: [running] if the generated code is unchanged, else a
/// restarted application with the new beans and the same arguments;
/// [runners]: whether ApplicationRunner / CommandLineRunner beans run again.
ConfigurableApplicationContext reloadApplication(
ConfigurableApplicationContext running, {
bool runners = true,
}) => springApplication.reload(running, runners: runners);
/// Like [reloadApplication], reading config files asynchronously.
Future<ConfigurableApplicationContext> reloadApplicationAsync(
ConfigurableApplicationContext running, {
bool runners = true,
}) => springApplication.reloadAsync(running, runners: runners);
A hot reload replaces method bodies but does not run main again, so a context built before the reload keeps its old beans. To decide whether that matters, the generator writes a fingerprint: an FNV-1a hash of the generated code (the library and its files), written into the debug part and passed by springApplication in debug and profile builds. After a reload, reload compares the fingerprint of the new code with the one the running context was started from:
- The same. Only method bodies changed, and the generated code did not. The running context is returned as it is, and the beans keep their state.
- Different. Beans, annotations or files of
lib/resources/changed (the resources are embedded in the file, so they change the hash too). The context is closed and the application starts again with the same arguments;runners: falseskips theApplicationRunnerandCommandLineRunnerbeans on that restart.
What stays in every build, on purpose: runApplication's hotReload: () => springApplication (it is also how the context starts the same application in another isolate, used by the web server's server.isolates.count), the getters springApplication and $application, and the beans' source: strings (start-up errors and the actuator read them).
The hash is computed over the generated text itself, so it is the same on every machine and from one build to the next, as long as the code is the same. You rarely call these functions: SpringApplicationWidget calls them on a Flutter hot reload, and on the Dart VM the runtime restarts contexts started by runApplication when the development tool asks it to.
exclude and excludeName
@SpringBootApplication takes two lists that switch off auto-configuration:
@SpringBootApplication(
exclude: [CacheAutoConfiguration],
excludeName: ['springBootStarterFeignAutoConfiguration'],
)
void main(List<String> args) => runApplication(args);
The generator copies them into springApplication, as references to the classes and as strings:
SpringApplication get springApplication => SpringApplication(
[$application],
autoConfigurations: [/* ... */],
exclude: [CacheAutoConfiguration],
excludeName: [r'springBootStarterFeignAutoConfiguration'],
// ...
);
The runtime does the rest. exclude lists @AutoConfiguration classes; a type that is not one fails the start. excludeName takes the name of an @AutoConfiguration class or of a whole module (which removes everything the starter adds); unknown names are ignored. The property spring.autoconfigure.exclude adds names without a rebuild.
Embedded resources
The files of lib/resources/ are embedded into $application as resources:, so application.properties, message bundles and templates are found on every platform. An application whose main is outside lib/ also gets the lib/resources/ of each directory between the package root and main, the nearest winning. An application with the actuator also gets a build-info.properties. See Embedded resources.
--dart-define keys
A program compiled for Flutter, the web or AOT can only read a --dart-define with a constant key. So springApplication lists every property the application may read, in both forms (greeting.punctuation and GREETING_PUNCTUATION), each behind if (const bool.hasEnvironment(...)). Only the defines given at build time end up in the map, as a property source right below the command-line arguments. See --dart-define keys.
Rules and errors
- One
@SpringBootApplicationper file. A second one in the same file fails the build:Only one @SpringBootApplication is allowed per file. - Several entry points in one package (
bin/server.dart,bin/worker.dart) each get their own generated file, each scanninglib/andbin/. - Do not put a
@ComponentScanvariable in the file ofmain. The application wins: the file gets the application's output, and the getter the variable reads is never generated. - Bean names must be unique, and the other build-time checks apply, as for any module.
In Spring (Java)
@SpringBootApplication(exclude = CacheAutoConfiguration.class)
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
Differences:
@SpringBootApplication()goes on themainfunction, not on a class.- The component scan covers
lib/and the directory ofmain, not a Java package and its subpackages. - The auto-configurations are found at build time in each dependency's
lib/spring_auto_configuration.dart, not at startup inMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Runbuild_runnerafter you add or remove a starter. - Hot reload compares a fingerprint of the generated code, where Spring Boot DevTools restarts when class files change on disk.