
# 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 analyzer sees every declaration with its resolved types and the constant values of its annotations, which is everything Spring reads with reflection;
- the result is ordinary Dart (constructor calls, closures, constants), so the compiler can check it, tree-shake it and minify it like your own code;
- mistakes that Spring finds at startup (a misplaced annotation, a pointcut that does not parse, a type the generated code cannot name) become build errors that point at your source.

## The pieces

```text
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](#where-the-files-go)). |
| `runs_before` | on three builders | The only ordering the generator asks for (see [the order](#the-order-of-the-builders)). |

## 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](builders.md)).

## 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](../spring-core-dart/beans/object-methods.md) |
| `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/`:

```dart
// 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.

- `@ComponentScan` anywhere but on a top-level variable (a class, a function, a field, ...) fails the build with an example of the correct form.
- If a top-level function has `@SpringBootApplication` (matched by URL, from `spring_boot_dart`), the step builds [an application](spring-boot-application.md). More than one in a file fails the build.
- Else, if a top-level variable has `@ComponentScan`, the step builds [a module](component-scan.md). More than one in a file fails the build, and so does a private variable or one whose name starts with `$`.
- Else nothing is written.

### 3. Finding the files to scan

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

- for a `@ComponentScan` file, the directory of that file;
- for a `@SpringBootApplication` file, `lib/` and the directory of `main` (only `example/` for an entry point under `example/`).

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](component-scan.md#nested-scans)).

### 4. Reading resources

The files of `lib/resources/` are read, to be embedded as text or base64 (see [Embedded resources](resources.md)). 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:

- **`@Bean` method bodies.** A `@Bean` method declared to return `DataSource` that returns `HikariDataSource(url)` registers a `HikariDataSource`. The body is read to find the real type.
- **Field initializers**, for the values a class gives its fields.
- **Calls to the `ObjectMapper`**, to know which classes are read from or written to JSON, so that only what is used gets introspection (see [Only what runs](optimizations/introspection.md)).

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](checks.md).

### 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](optimizations/aop-proxies.md)). For an application it also reads the `lib/spring_auto_configuration.dart` of every dependency, to list the [auto-configurations](auto-configurations.md).

### 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:

```dart
// 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](spring-boot-application.md#hot-reload)).

### 8. Writing

The text is written to the output path. If the step failed, the existing file is kept (see [below](#when-the-sources-have-errors)).

## 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`).

- **A part runs only when the application reaches its package**, listed in its `pubspec.yaml` or brought by a package it lists. Without the Flutter starter none of the Flutter code runs, and without the data starter none of the data code.
- **The parts are listed once**, in `lib/src/packages.dart`, in the order the builders ask them. That order is the order of what they write and of the errors they report.
- **A part can be left out by a build key**, as an auto-configuration module can: `PackageBuild` is read as `AutoConfigurationBuild` is (see [Parts of the generator by key](optimizations/build-conditions.md#parts-of-the-generator-by-key)). No built-in part takes a key yet.
- **The generated code did not change** when the generator was split into parts, and a clean build takes the same time.
- There is no public registration for parts from outside the framework yet.

| 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](../spring-boot-starter-data/optimizations.md).

## The other builders

The other builders do not run per file:

- `spring_test` runs per `test/*_test.dart` file. It only parses the file (no resolution), and writes nothing unless it finds `@SpringBootTest` or `@DataTest` classes.
- `spring_metadata`, `spring_flutter_keys`, `spring_flutter_web`, `spring_flutter_page_loader`, `spring_flutter_seo` and `spring_flutter_deep_links` run once per package (their input is `build_runner`'s `$package$` placeholder). Each one first checks whether the package needs it, and otherwise writes nothing.

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](builders.md).

## 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:

- changing a bean class under a scan root regenerates the module of that root. The application's step runs again too, since it resolves the libraries of the modules it imports, but its file only changes when what it writes changes;
- adding a file to a scanned directory regenerates that module, because the glob result changed;
- changing a file of `lib/resources/` regenerates every output that embeds it;
- changing a file no step read (a file outside the scan roots that nothing scanned imports) regenerates nothing.

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:

- it remembers the last content it generated for each output;
- while you type, a scanned library often has syntax errors. The builder then writes the last good content again, so the generated file does not change, and logs one warning per output until the next successful generation;
- a validation error (an annotation in the wrong place, a bad pointcut) is reported as the build error, and the file stays as it was.

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](errors.md).

## 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.

```yaml
# 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](builders.md) 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

- [The builders](builders.md)
- [@ComponentScan modules](component-scan.md)
- [Build speed](optimizations/build-speed.md)
- [BeanModule](../spring-core-dart/beans/bean-module.md)
