
# Auto-configurations

A starter adds beans to every application that depends on it, without any code in the application. It does so with an **auto-configuration module**: a `BeanModule` variable annotated `@AutoConfigurationModule()` in the starter's `lib/spring_auto_configuration.dart`. When the generator writes an application's `@SpringBootApplication` output, it looks for these modules in every package the application depends on and passes them to the generated `springApplication`.

## Why

Spring Boot finds auto-configuration at startup: it reads the `META-INF/spring/...AutoConfiguration.imports` files of the class path. Dart has no class path to read at run time, and no reflection on Flutter, the web or AOT executables. So the generator does this step at build time: it reads a file of fixed name in each dependency and writes plain references to the modules it finds.

The consequence: adding a starter to `pubspec.yaml` is enough, but the application must be built again (`dart run build_runner build`) for the starter's modules to appear.

## Declaring a module (starter authors)

A starter puts its modules in `lib/spring_auto_configuration.dart`. The file name is fixed. Each module is a **public top-level variable** of type `BeanModule` with `@AutoConfigurationModule()`. Usually the module comes from a `@ComponentScan` of the starter's own `lib/`:

```dart
// lib/src/cache_beans.dart of the package `neon_cache`
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:neon_cache/spring_gen/src/cache_beans.spring.dart';

// Every bean class under lib/src/ is in this module.
@ComponentScan()
final BeanModule neonCacheBeans = $neonCacheBeans;
```

```dart
// lib/src/cache_auto_configuration.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';

@AutoConfiguration()
class CacheAutoConfiguration {
  @Bean()
  @ConditionalOnMissingBean() // the application's own Cache wins
  Cache cache(@Value(r'${neon.cache.size:100}') int size) => InMemoryCache(size);
}
```

```dart
// lib/spring_auto_configuration.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:neon_cache/src/cache_beans.dart';

@AutoConfigurationModule(requires: '^0.7.0')
final BeanModule neonCacheAutoConfiguration = neonCacheBeans;
```

A hand-written `BeanModule(...)` works as well; `spring_boot_starter_flutter` writes its modules by hand.

A module's name, used by `before`, `after` and `excludeName`, is the name of its `BeanModule`. For a `@ComponentScan` module that is the scan variable's name (`neonCacheBeans` above), whatever the variable of `spring_auto_configuration.dart` is called. The starters of Spring for Dart give both the same name (`springBootStarterCacheAutoConfiguration`).

`@AutoConfigurationModule` takes these arguments, all optional:

| Argument | Type | Default | Meaning |
|---|---|---|---|
| `order` | `int` | `0` | Position among the auto-configuration modules, lower first (Spring Boot's `@AutoConfigureOrder`). |
| `before` | `List<String>` | `[]` | Modules, or `@AutoConfiguration` classes by short name, registered after this one, so their conditions see its beans. Unknown names are ignored. |
| `after` | `List<String>` | `[]` | Modules, or `@AutoConfiguration` classes by short name, registered before this one. Unknown names are ignored. |
| `requires` | `String?` | `null`: any version | The `spring_boot_dart` versions the starter works with, as a pub version range (`^0.7.0`, `'>=0.7.0 <0.9.0'`). Checked at build time. |
| `build` | `AutoConfigurationBuild?` | `null`: always | Lets a property of the application decide whether the module is in the build. See [Modules left out of the build](optimizations/build-conditions.md). |
| `platform` | `ModulePlatform?` | `null`: everywhere | `native`, `web` or `server`: the module is listed under a constant of that platform, and another platform's compiler drops it. See [Modules of one platform](optimizations/build-conditions.md#modules-of-one-platform). |
| `factories` | `List<Object>` | `[]` | Constants the application finds by type before any bean exists, copied into the generated application. See [Factories](#factories). |

## How the application finds the modules

When the generator builds an application (a library whose `main` has `@SpringBootApplication()`), it does the following:

1. **It lists the reachable packages.** It reads the application's `pubspec.yaml`: its `dependencies` (and its `dev_dependencies` too when the entry point is outside `lib/` and `bin/`, such as `example/` or `tool/`). Then it reads the `dependencies` of each of those packages' `pubspec.yaml`, and so on. In a pub workspace the package configuration lists every member of the workspace; only the packages reached this way count, so an app never gets the modules of a sibling it does not depend on. When a `pubspec.yaml` cannot be read, the generator falls back to every package of the configuration rather than miss a module.
2. **It reads each reachable package's `lib/spring_auto_configuration.dart`**, if it has one. The application's own package is skipped, except for an entry point under `example/`: the example of a starter uses the starter's own modules, as any application depending on it would.
3. **It takes every top-level variable annotated `@AutoConfigurationModule`.** For each one it checks `requires` (below), and decides `build` (see [Modules left out of the build](optimizations/build-conditions.md)).
4. **It sorts them by package name, then by variable name**, so the output is the same on every machine.
5. **It writes them into `springApplication`**, with the `order`, `before`, `after` and `factories` of the modules that set any.

The output, simplified by dropping the import prefixes (`_i63.`):

```dart
// bin/spring_gen/main.spring.dart (generated)
SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [
    neonCacheAutoConfiguration,                // package neon_cache
    springBootAutoConfiguration,               // package spring_boot_dart
    springBootStarterLoggingAutoConfiguration, // package spring_boot_starter_logging
  ],
  autoConfigurationMetadata: {
    neonCacheAutoConfiguration: const AutoConfigurationModule(
      order: 5,
      after: ['springBootAutoConfiguration'],
    ),
  },
  // dartDefines, fingerprint (debug and profile builds)
);
```

A module without `order`, `before`, `after` and `factories` gets no entry in `autoConfigurationMetadata`; the map is left out when no module sets them.

## The order of registration

The list the generator writes is sorted by package and name only. The order in which the modules are **registered** is decided by `SpringApplication` at every start, as Spring Boot's `AutoConfigurationSorter` does:

1. by `order` (`0` when the module has no entry), then by name;
2. then `before` and `after` move modules around. A cycle among them fails the start.

The auto-configuration modules are registered after the application's own beans, so a `@ConditionalOnMissingBean` in a starter sees the application's beans and backs off.

## The `requires` check

`requires` is the range of `spring_boot_dart` versions a starter was made for. The generator compares it with the version in use (the constant `springBootVersion` of `spring_boot_dart`) and stops the build when they do not match, instead of failing later with errors in generated or runtime code. This is the job Spring Boot's BOM and Spring Cloud's compatibility verifier do in Java.

The check runs for every module found, also for one that a build condition leaves out.

| Situation | Build error |
|---|---|
| The range does not allow the version in use | `Incompatible starter: neon_cache requires spring_boot_dart ^0.8.0, but 0.7.1 is used.` followed by `Upgrade spring_boot_dart to a version in ^0.8.0, or use a version of neon_cache made for spring_boot_dart 0.7.1 (see its CHANGELOG / pub.dev versions).` |
| The range does not parse | `neon_cache: invalid requires 'not a range' (...).` |
| `spring_boot_dart` is not a dependency of the application | `neon_cache requires spring_boot_dart ^0.7.0, but spring_boot_dart is not a dependency of this application.` |

The error points at the module variable in the starter.

## Factories

The `factories` of an `@AutoConfigurationModule` are constants the application finds by type before any bean exists (see [Factories](../spring-boot-dart/auto-configuration.md#factories)). Spring Boot reads such entries from `META-INF/spring.factories` on the class path at run time, with `SpringFactoriesLoader.loadFactories(type, classLoader)`. Dart has no class path to scan, so the generator copies each factory into the `autoConfigurationMetadata` of the generated `springApplication`, as the constant it was written as, imported from its own package:

```dart
// lib/spring_auto_configuration.dart of spring_boot_starter_flutter_material
@AutoConfigurationModule(factories: [MaterialThemeDesign()])
final BeanModule springBootStarterFlutterMaterialAutoConfiguration = BeanModule(/* ... */);
```

```dart
// lib/spring_gen/main.spring.dart of an app (generated, without the import prefixes)
autoConfigurationMetadata: {
  springBootStarterFlutterMaterialAutoConfiguration: const AutoConfigurationModule(
    factories: [MaterialThemeDesign()],
  ),
},
```

A factory must be a public constant that the generated file can name:

| Factory | Written as |
|---|---|
| A `const` constructor call with literal arguments (`null`, a bool, a number, a text) or arguments that are such constants themselves | the same call: `MaterialThemeDesign()` |
| A call of a named constructor | the same call: `OceanThemeDesign.dark()` |
| A top-level `const` variable | its name: `oceanThemeDesign` |
| A `static const` field | the class and the field: `OceanThemeDesign.standard` |

Anything else stops the build: a private class or constant, one declared outside the `lib/` of its package, a value that is no such constant. The error says what a factory can be: `AutoConfigurationModule.factories: OceanThemeDesign cannot be written into the generated application. A factory is a public constant: a const constructor call with literal arguments, a top-level const variable or a static const field.`

The application has the factories of a starter once it is generated again: run `build_runner` after adding a starter that has some (the Flutter design starters, `spring_boot_starter_flutter_material` and `spring_boot_starter_flutter_cupertino`, have one each).

## `exclude` and `excludeName`

An application switches off auto-configuration with the arguments of `@SpringBootApplication`:

```dart
// bin/main.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:neon_cache/neon_cache.dart'; // exports CacheAutoConfiguration

import 'spring_gen/main.spring.dart';

@SpringBootApplication(
  // An @AutoConfiguration class, by type.
  exclude: [CacheAutoConfiguration],
  // A whole module, by its BeanModule name.
  excludeName: ['springBootStarterCacheAutoConfiguration'],
)
void main(List<String> args) => runApplication(args);
```

The generator passes both lists on as they are:

```dart
// generated
SpringApplication get springApplication => SpringApplication(
  [$application],
  autoConfigurations: [/* ... */],
  exclude: [CacheAutoConfiguration],
  excludeName: ['springBootStarterCacheAutoConfiguration'],
  // ...
);
```

`SpringApplication` applies them at every start, together with the property `spring.autoconfigure.exclude`:

- `excludeName` matches a module by its `BeanModule` name (which removes everything the starter adds), or an `@AutoConfiguration` class by its short or full name. An unknown name is ignored, so a name may stay after the starter is removed.
- `exclude` names `@AutoConfiguration` classes. A type that is no auto-configuration class fails the start.

An exclusion works at run time: the excluded module's code is still compiled into the app. To keep a module's code out of the app, the starter must declare a [build condition](optimizations/build-conditions.md).

## Modules left out of the build

A starter can let the application decide, at build time, whether a module is in the app at all:

```dart
@AutoConfigurationModule(
  build: AutoConfigurationBuild('spring.flutter.debug.enabled'),
)
final BeanModule springBootStarterFlutterDebugAutoConfiguration = BeanModule(/* ... */);
```

With the property `true` the module is listed as above; with `false` it is not listed and leaves no trace in the generated code; not set, it is listed under `if (!const bool.fromEnvironment('dart.vm.product'))`, so a release build compiles it away. Everything about it is on [Modules left out of the build](optimizations/build-conditions.md).

## Modules of one platform

A module with `platform: ModulePlatform.native` is listed under `if (const bool.fromEnvironment('dart.library.io'))`, one with `ModulePlatform.web` under `if (const bool.fromEnvironment('dart.library.js_interop'))`. The compiler of the other platform sees the constant `false` and drops the module with everything only it reaches: a browser build carries no server code, though the same generated file lists the server's modules. The web starter, the security starter, the actuator starter and the server half of the WebSocket starter are `native`. The full table is on [Modules of one platform](optimizations/build-conditions.md#which-modules-are-marked). One with `ModulePlatform.server` (code that must not ship in an app, such as the Supabase starter's admin API) is listed under `if (const bool.fromEnvironment('dart.library.io') && !const bool.fromEnvironment('dart.library.ui'))`, so a Flutter app drops it too.

## See also

- [The application: @SpringBootApplication](spring-boot-application.md)
- [Modules left out of the build](optimizations/build-conditions.md)
- [AOP proxies: pruning and deferring](optimizations/aop-proxies.md)
- [Build-time checks](checks.md)
- [Bean modules](../spring-core-dart/beans/bean-module.md)
- [Conditions](../spring-core-dart/beans/conditional.md)
