How the generation works

dart run build_runner build starts build_runner, which runs the builders of every package your package depends on. spring_core_dart_generator registers nine builders. This page follows the main one, spring_core_dart, from your source file to the formatted .spring.dart file, and explains how the others fit around it.

Why build time

Spring reads annotations with reflection when the application starts. Dart has no reflection in Flutter, in AOT executables or on the web, so the generator does the same work during the build, with the Dart analyzer:

The pieces

dart run build_runner build
        │
        ▼
build_runner ── reads build.yaml of spring_core_dart_generator
        │       auto_apply: dependents  → runs in every package that depends on it
        │       build_to: source        → writes next to your code, not into .dart_tool/
        ▼
┌──────────────────────────────── per package ────────────────────────────────┐
│ spring_properties (off by default)                                          │
│        │ runs_before                                                        │
│        ▼                                                                    │
│ spring_core_dart   ── one step per .dart file of lib/ bin/ test/ example/   │
│ spring_test        ── one step per test/*_test.dart                         │
│ spring_flutter_keys, spring_flutter_web, spring_flutter_deep_links          │
│ spring_metadata ─────────────┐ runs_before                                  │
│ spring_flutter_page_loader ──┤                                              │
│                              ▼                                              │
│ spring_flutter_seo                                                          │
└─────────────────────────────────────────────────────────────────────────────┘

Each builder entry of the generator's build.yaml has:

Setting Value Effect
auto_apply dependents (all but spring_properties, which is none) The builder runs in every package that has spring_core_dart_generator as a dependency. You write no build.yaml.
build_to source Outputs are written into your package, next to the sources, so you can read, commit and publish them.
build_extensions per builder Which inputs a builder looks at and which files it may write (see the path mapping).
runs_before on three builders The only ordering the generator asks for (see the order).

The order of the builders

build_runner runs builders in phases: each builder applied to a package is one phase. A step can read the files earlier phases wrote, but not what other steps of its own phase write. The generator declares three constraints with runs_before:

Builder Runs before Why
spring_properties spring_core_dart A hand-written starter imports, from its own lib/, the module generated for its @ConfigurationProperties classes, and its example imports that lib/. The example's step (main builder) could not read a file written in its own phase, so the lib/ part is generated one phase earlier.
spring_metadata spring_flutter_seo The site's pages are made from the routes listed in spring_metadata.json.
spring_flutter_page_loader spring_flutter_seo Each page of the site is a copy of web/index.html with its page loader already in it.

The order of the other builders is left to build_runner. Nothing depends on it, with one exception that is handled without ordering: the typed keys of a Flutter app (theme.spring.keys.dart, messages.spring.keys.dart) are part files of the main builder's output, written by spring_flutter_keys in its own phase. The main builder cannot check whether those files exist, so it decides the part lines with the same computation the keys builder uses. This is why spring_flutter_keys must not be disabled while the main builder runs (see The builders).

Where the files go

The main builder may write one file for each .dart file of four source roots. The file goes into the spring_gen/ folder at the top of the root, with the rest of the path mirrored and .dart replaced by .spring.dart:

Your file Generated file
lib/main.dart lib/spring_gen/main.spring.dart
lib/src/a.dart lib/spring_gen/src/a.spring.dart
lib/src/shop/cart.dart lib/spring_gen/src/shop/cart.spring.dart
bin/main.dart bin/spring_gen/main.spring.dart
test/app/app.dart test/spring_gen/app/app.spring.dart
example/main.dart example/spring_gen/main.spring.dart
example/shop/bin/main.dart example/spring_gen/shop/bin/main.spring.dart
test/shop_test.dart (test builder) test/spring_gen/shop.test.spring.dart

Beside a .spring.dart file the builder writes a file for each other kind of generated code, only when the module has some of it. lib/src/a.dart can give, in lib/spring_gen/src/:

File Holds
a.spring.dart the bean definitions and the wiring
a.spring.introspection.dart a library with the descriptions of the classes the module uses ($<module>Introspections), and the copyWith of the object methods
a.spring.properties.dart a library with the binding of the @ConfigurationProperties classes: the descriptions only their binder uses
a.spring.proxies.dart a part of the module's library: the AOP proxy classes and the lazy-resolution proxies
a.spring.debug.dart for a @SpringBootApplication only, a part of its library: the fingerprint and the reload functions, which only debug and profile builds use

The names follow one convention, <name>.spring.<kind>.dart, as theme.spring.keys.dart and json_schemas.spring.classes.dart do.

The .spring.dart file imports the two libraries and hands their lists to the module. Your own files never need an import, an export or a part line for them, except where you call copyWith.

Files in other directories (tool/, web/, ...) get no generated file, and files that already end in .spring.dart are never inputs.

Keeping the generated files in one folder per root keeps them out of your way, and lets you exclude them from the analyzer or from code review in one line. Import them with a relative path from the file next to them, or with a package: URI from lib/:

// bin/main.dart
import 'spring_gen/main.spring.dart';

// lib/src/beans.dart
import 'package:my_app/spring_gen/src/beans.spring.dart';

One step of the main builder

build_runner calls the main builder once for every .dart file of lib/, bin/, test/ and example/. Most calls end at once.

1. A cheap text check

The builder reads the file as text. If it contains neither ComponentScan nor SpringBootApplication, the step ends: the file is not resolved and no output is written. This keeps the build fast in large packages.

2. Resolving the library

Otherwise the file is resolved with the analyzer, which gives its element model: the library's classes, functions and top-level variables, with resolved types and annotation values.

3. Finding the files to scan

The file's location decides which files belong to the output. This directory is the scan root:

Every .dart file below the scan roots is found with a glob and sorted by path, so the output is the same on every machine. Generated .spring.dart files are left out. A file below the roots that declares its own @ComponentScan owns its directory: its files are left out, and its module is imported instead (see nested scans).

4. Reading resources

The files of lib/resources/ are read, to be embedded as text or base64 (see Embedded resources). For a Flutter app, the builder also decides the part lines of the typed key files.

5. Scanning: from elements to models

Each library is resolved, and the scanner turns its declarations into models: one bean model per component class and @Bean method, with its constructor, injection points, conditions, lifecycle methods, event listeners and proxy, plus models for @Configurable classes, introspection, @PropertySource, @Log, data repositories and Flutter widgets.

Some answers need more than the element model, so the builder also resolves the syntax tree of a few bodies before it scans a library:

The scanner also validates every declaration. An error does not stop the scan: the problems of all libraries are collected and reported together. After the scan, the builder checks that two unconditional beans do not share a name or alias, checks @Value('asset:...') values against pubspec.yaml, and then fails the build if any problem was found. See Build-time checks.

6. AOP

The builder decides which beans get a generated proxy class. In an application it knows the advice of every module, so it can leave out the proxy of a bean no pointcut can match (see AOP proxies). For an application it also reads the lib/spring_auto_configuration.dart of every dependency, to list the auto-configurations.

7. Emitting and formatting

The emitter turns the models into Dart with code_builder:

  1. the generated classes (AOP proxies, which go to the .spring.proxies.dart part, @Configuration and @Lookup subclasses, repository classes);
  2. the getter BeanModule get $<name> with one BeanDefinition per bean, the embedded resources, the imported modules and the other module arguments;
  3. the descriptions of the introspected classes, which go to their own library, .spring.introspection.dart, and those only the @ConfigurationProperties binder uses, in .spring.properties.dart;
  4. for an application, springApplication, runApplication and the hot reload functions;
  5. the BuildContext extension (Flutter) and the @Log extensions.

Every library is imported with a prefix (_i1., _i2., ...), so a name in your code can never clash with a generated name. Where a scanned library imports a type through a package's public library, the generated file does the same rather than importing the package's src/ file. The result is formatted with dart_style and starts with a header:

// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated by spring_core_dart_generator from @ComponentScan.

// ignore_for_file: type=lint, implementation_imports, unnecessary_cast
// ignore_for_file: deprecated_member_use, invalid_use_of_visible_for_testing_member
// ignore_for_file: invalid_use_of_internal_member, invalid_use_of_protected_member

The generated code has no analyzer warnings. Lints are still ignored in it (type=lint), because your own lint set may be stricter than the one the generator is tested with.

For an application, the builder then computes a hash of the generated code (the library and its files) and writes it into the debug part, main.spring.debug.dart, as _$fingerprint; springApplication passes it as fingerprint: in debug and profile builds only. On hot reload, the runtime compares it with the running context's to decide whether the context must restart (see @SpringBootApplication).

8. Writing

The text is written to the output path. If the step failed, the existing file is kept (see below).

The core's folders

The core of the generator (lib/src/core/) is split by concern, as spring_core_dart's lib/src is:

Folder Holds
beans/ the bean scan and model, the module's emitter, the @Configuration and @Lookup subclasses, @Log
aop/ pointcuts, advisors, proxy decisions
introspection/ its own scanner, model and emitter: what a class needs described, the JSON and validation checks, the object methods, the JSON Schemas
properties/ property keys for --dart-define, Dart names
spel/ SpEL compiled to Dart
metadata/ spring_metadata.json
builder/ the builders, the build-time configuration, the build keys, the parts' interface

The bean scan and the packages' parts do not build descriptions. They tell introspection what a class needs (the result of a controller is written out, a request body is read in, a method is called by an expression), and introspection describes the class once, for all of them.

Parts of the packages

The core scans the beans, writes their definitions, proxies and introspections and checks them. It names no other package's part. What a package adds is its part, a PackageGeneration, in lib/src/<part>/ of the generator (data/, flutter/, navigation/, ...). It is a package's, not a starter's: several parts belong to libraries (spring_web_dart, spring_security_core, spring_boot_actuator).

Part Waits for What it does
Data metadata spring_boot_starter_data The entities and repositories of spring_metadata.json.
Flutter spring_boot_starter_flutter Spring widgets, loader kinds, the SpringWidgetBindings bean, the BuildContext getters, the asset check.
Navigation spring_boot_starter_flutter_navigation @ScreenRoute and @RouteShell: the ScreenRoutes bean and the screens' constants.
Change notifier spring_boot_starter_flutter @ChangeNotifierComponent: the proxy mixes ChangeNotifier in.
Signals spring_boot_starter_flutter_signals Fails the build for @Signal, @Computed and @Effect that cannot be followed.
Web spring_web_dart What request mappings and @ExceptionHandler do with their values.
WebSocket spring_boot_starter_websocket What an endpoint's handlers and sendJson do with their values.
Scheduling spring_boot_starter_scheduling What @Scheduled methods need described (nothing).
Security spring_security_core Where the expressions of the method security annotations look.
Cache spring_boot_starter_cache Where the cache annotations' expressions look; no cached Stream.
Actuator spring_boot_actuator build-info.properties among an application's resources.
Data spring_boot_starter_data Entities, repositories, the drivers' glue and their checks.

The JSON Schemas of spring.json.schemas are the core's, not a part: they are asked in every build, and their part file comes after the parts'. Each starter's page What a build contains says which parts run for it, for example the data starter's.

The other builders

The other builders do not run per file:

The four Flutter builders that write into your own files (web_dev_config.yaml, web/index.html, web/, Info.plist, AndroidManifest.xml, ...) declare no outputs to build_runner. A declared output would be deleted by build_runner when the builder stopped writing it, and it would overwrite a file of the same name that you wrote by hand. These builders manage their files themselves, between markers or behind a header, and never touch content they did not write. See The builders.

Incremental builds

build_runner records every file a step reads: the input, the libraries it resolves (and what they import), the files a glob found, pubspec.yaml, the files of lib/resources/. On the next build, a step runs again only if one of them changed. In practice:

The output does not depend on the time or the machine: files are sorted by path, keys are sorted, and nothing is written from the clock (an actuator app's generated build-info.properties has no build time, for this reason). A build with no change in the sources writes the same bytes, so the generated files only show up in git diff when something really changed.

On watch

dart run build_runner watch keeps one build running and rebuilds when a file changes. The builder object lives as long as the process, and the main builder uses that:

So your editor does not see the generated file vanish and every file that imports it turn red on each keystroke.

When the sources have errors

Situation With an existing generated file Without one (a cold build)
A scanned library has syntax errors The file is kept, one warning is logged The build fails
A validation error or a crash on code with errors The file is kept, the error fails the build The build fails
A test file has syntax errors (spring_test) The file is kept, a warning is logged Nothing is written, a warning is logged

The existing file is read from the directory of its own package, also when dart run build_runner build --workspace builds every package of a pub workspace from one directory. More on this in Errors and the generated files.

Limiting the builders

A package can narrow or switch off a builder in its own build.yaml with build_runner's usual settings. The starters of Spring for Dart do this: only their example is an application, the rest is written by hand.

# build.yaml of spring_boot_starter_web
targets:
  $default:
    builders:
      spring_core_dart_generator:spring_core_dart:
        generate_for: [example/**, test/app/**]
      spring_core_dart_generator:spring_properties:
        enabled: true
        generate_for: [lib/src/config/**]
      spring_core_dart_generator:spring_test:
        enabled: false

See The builders for what each builder does and which ones must stay on.

In Spring (Java)

Spring scans the classpath when the context starts. ClassPathBeanDefinitionScanner reads the class files of the base packages, ConfigurationClassPostProcessor parses @Bean methods, and reflection creates the beans. Spring 6 AOT can instead run this analysis during the build (BeanFactoryInitializationAotProcessor) and write Java source that registers the beans, mainly for GraalVM native images. The generator always works like Spring AOT, because Dart offers no other way on most platforms.

See also