
# Auto-configuration and starters

A starter is a library that brings ready-made beans: add it to `pubspec.yaml`, run `build_runner`, and its feature is there with no code of yours. It ships them as *auto-configuration*: beans registered after the application's own, guarded by [conditions](conditions.md) so that your own bean always wins.

## Why

A web server, a cache or a logging setup needs a dozen beans wired the right way. Writing them in every application is repetitive and error-prone. With auto-configuration, the library writes them once, and each application overrides only what it wants: declare your own `Cache` bean and the starter's `@ConditionalOnMissingBean(Cache)` backs off.

## Example

A starter `neon_cache`:

```dart
// lib/spring_auto_configuration.dart of package neon_cache (the file name is fixed)
import 'package:spring_boot_dart/spring_boot_dart.dart';

import 'spring_gen/src/cache.spring.dart';

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

```dart
// lib/src/cache.dart of neon_cache
@AutoConfiguration()
class CacheAutoConfiguration {
  @Bean()
  @ConditionalOnMissingBean(Cache)                       // the application's own Cache wins
  @ConditionalOnProperty('neon.cache.enabled', matchIfMissing: true)
  Cache cache(@Value(r'${neon.cache.size:100}') int size) => InMemoryCache(size);
}
```

An application that depends on `neon_cache` gets a `Cache` bean with no code. One that declares its own gets only its own:

```dart
// The application's bean: the starter's cache() is not registered.
@Bean()
Cache cache() => RedisCache();
```

## How starters are found

When an application with `@SpringBootApplication()` is built, the generator walks every package of its dependency graph, direct and transitive, reads `lib/spring_auto_configuration.dart` where there is one, and lists the annotated modules in the generated `springApplication`:

```dart
// bin/spring_gen/main.spring.dart of the application (generated)
SpringApplication get springApplication => SpringApplication(
      [$application],
      autoConfigurations: [
        neonCacheAutoConfiguration,   // found in neon_cache
        springBootAutoConfiguration,  // spring_boot_dart
      ],
      // only where a starter sets order, before, after or factories
      autoConfigurationMetadata: {
        neonCacheAutoConfiguration: AutoConfigurationModule(order: 10),
      },
    );
```

- Discovery happens at build time, not by scanning a classpath at start-up. After adding a starter, run `build_runner` again.
- Only `@SpringBootApplication` applications discover modules. An application that creates its context by hand lists the modules itself.

## @AutoConfigurationModule

On a public top-level `BeanModule` variable of `lib/spring_auto_configuration.dart`.

| Parameter | Default | Meaning |
|---|---|---|
| `order` | `0` | The position among the modules, lower first (Spring Boot's `@AutoConfigureOrder`) |
| `before` | `[]` | Modules, or `@AutoConfiguration` classes by short name, that must be registered after this one |
| `after` | `[]` | Modules or classes that must be registered before this one: `['springBootAutoConfiguration']` |
| `requires` | `null`: any | The `spring_boot_dart` versions the starter works with, as a pub range (`^0.7.0`). A mismatch stops the build (see [Versions](compatibility.md)) |
| `build` | `null`: always | An `AutoConfigurationBuild`: a property of the application's configuration decides whether the module is in the build at all |
| `platform` | `null`: everywhere | A `ModulePlatform`: `native`, `web` or `server`. On another platform the compiler drops the module and everything only it reaches |
| `factories` | `[]` | Constants the application finds by type before any bean exists. See [Factories](#factories) |

`@AutoConfiguration()` marks a configuration class of a starter; it is a `@Configuration` whose `@Bean` methods are registered with auto-configuration.

## The order of registration

1. The application's own classes, first.
2. The auto-configuration modules, sorted as Spring Boot's `AutoConfigurationSorter`: by `order`, modules of the same order by name, then `before` and `after` move them. A cycle stops the start with `AutoConfigure cycle detected between ...`. Unknown names are ignored.

```dart
@AutoConfigurationModule(
  order: 10,
  after: ['springBootAutoConfiguration'],    // a module or an @AutoConfiguration class
  before: ['neonMetricsAutoConfiguration'],
)
final BeanModule neonCacheAutoConfiguration = $neonCacheBeans;
```

Bean conditions are decided class by class in that order, so `@ConditionalOnMissingBean` sees what the application declared, including the beans of its `@Import`ed registrars. See [Conditions](conditions.md#when-bean-conditions-are-decided).

## Excluding auto-configuration

When a starter's beans are not wanted, exclude them before their conditions run:

```dart
@SpringBootApplication(
  exclude: [CacheAutoConfiguration],                     // by class
  excludeName: ['springBootStarterCacheAutoConfiguration'], // a module or a class name
)
void main(List<String> args) => runApplication(args);
```

```properties
# Adds to the annotation, at run time: comma list or YAML list
spring.autoconfigure.exclude=JacksonAutoConfiguration,CacheAutoConfiguration
```

- A `Type` in `exclude` is compared by its simple name, so classes of the same name in different libraries are excluded together.
- `excludeName` and the property take a module name (`springBootAutoConfiguration`), a short class name, or `package:x/src/y.dart#CacheAutoConfiguration`.
- Excluding a class removes its beans, its imported registrars and selectors, and its conditional `@PropertySource`s; configuration classes it `@Import`s stay. Excluding a module removes all of it.
- Excluding a type that is no auto-configuration stops the start; an unknown name is ignored.

The built-in ones are `JacksonAutoConfiguration`, `ValidationAutoConfiguration`, `MessageSourceAutoConfiguration`, `LifecycleAutoConfiguration`, `ApplicationAvailabilityAutoConfiguration`, `JsonSchemaAutoConfiguration` and `ObservationAutoConfiguration` (see [Built-in beans](built-in-beans.md)).

## Modules left out of the build

A feature only developers use (a debug panel) should not ship in a release. `build:` lets the application's configuration decide, when the generator runs, whether the module is in the application at all:

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

The property is read from `application.yml` and `application.properties` without a profile, when `build_runner` runs:

| Property | The module |
|---|---|
| `true` | in every build |
| `false` | in no build: no code at all |
| not set | `whenMissing` |

`whenMissing` is a `BuildInclusion`:

| Value | Meaning |
|---|---|
| `notInRelease` (default) | In debug and profile builds; a release compiles it away (`dart.vm.product`) |
| `always` | In every build |
| `never` | In no build |

A module the build puts in on a condition keeps its `order`, `before` and `after`. A build property set only in a profile file is warned about, since the build does not read profile files. See [Modules left out of the build](../spring-core-dart-generator/optimizations/build-conditions.md).

## Modules of one platform

Some code works on one platform only. A web server needs `dart:io`, which a browser does not have; code that reaches the browser through `dart:js_interop` cannot run on a server. `platform:` keeps a module to where its code works:

```dart
@AutoConfigurationModule(platform: ModulePlatform.native)
final BeanModule neonServerAutoConfiguration = BeanModule(/* ... */);
```

| `ModulePlatform` | Where the module is |
|---|---|
| `native` | Where `dart:io` exists: the Dart VM, an AOT executable, a Flutter app on a phone or a desktop. Not a browser |
| `web` | A browser, compiled to JavaScript or WebAssembly |
| `server` | The Dart VM or an AOT executable: `dart:io` exists and Flutter's `dart:ui` does not. Never a Flutter app, never a browser. For code that must not ship in an app, which anyone can read: an API that needs a secret key |
| not given | Everywhere |

The generated application lists such a module under a constant the compiler knows (`dart.library.io`, `dart.library.js_interop`, `dart.library.ui`). On another platform the constant is `false`: the compiler drops the module and all that only it reaches. So a Flutter web app whose dependencies bring `spring_boot_starter_web` carries no server code, and nothing has to be excluded by hand.

- It is not a runtime condition. On the other platform the module's beans are not skipped; they are not in the program.
- `platform:` combines with `build:`; the module is in when both say so.
- A program compiled with `-DSPRING_ALL_PLATFORMS=true` keeps every module whatever the platform: for server code run as JavaScript under Node on purpose.
- Use it for a whole module. A bean that differs by platform inside a module that is everywhere is chosen with a conditional import, as most starters do.
- Which modules of the family are marked is listed on [Modules of one platform](../spring-core-dart-generator/optimizations/build-conditions.md#which-modules-are-marked).

Spring has no counterpart: a JVM application runs on one platform.

## Factories

Beans exist once the context is created. A few things a starter adds must work earlier, while the environment is prepared or a Flutter app shows its splash. The design library a Flutter theme is read with is one: the themes are read for the splash, before any bean exists. A starter lists such things as constants in `factories`:

```dart
@AutoConfigurationModule(factories: [OceanThemeDesign()])
final BeanModule oceanAutoConfiguration = $oceanBeans;
```

The code that needs them asks for a type:

```dart
// In a listener of ApplicationEnvironmentPreparedEvent
final designs = event.springApplication.factories.load<ThemeDesign>();
```

- `SpringApplication.factories` is a `SpringFactories` that holds the factories of every module of the application. `load<T>()` gives those of type `T`: by `Ordered` where they implement it, else in the order of the modules. It is empty when no starter has one.
- The context has the same object as the `springFactories` bean.
- Each factory is a public constant: a `const` constructor call with literal arguments (a named constructor too), a top-level `const` variable or a `static const` field. The generator copies it into the generated `springApplication`; a factory in any other form stops the build with an explanation.
- An application gets the factories of a starter when it is generated: run `build_runner` again after adding a starter that has some.

Use factories only for what must exist before the beans. Everything else stays a bean, which an application can replace.

## Writing your own starter

Any package can be a starter.

1. **Declare the module** in `lib/spring_auto_configuration.dart`: a public top-level `BeanModule` variable with `@AutoConfigurationModule`.
2. **Describe the beans**, with the generator (`@AutoConfiguration`, `@Bean` and conditions, scanned by a `@ComponentScan` in the starter) or as hand-written `BeanDefinition`s. A hand-written definition needs a `source` (`library#Class`) or a `factoryMethodName` for its bean conditions to be decided in order; one with neither is decided at once.
3. **Publish the generated code.** The generator writes files only into the package being built, never into dependencies. Run `dart run build_runner build` in the starter and publish its `*.spring.dart` files.
4. **Test it** with `ApplicationContextRunner` from `spring_boot_starter_test`: alone, with an application bean that makes it back off, and with properties that switch it off.

```dart
// test/cache_auto_configuration_test.dart
test('backs off when the application has a Cache', () {
  const ApplicationContextRunner()
      .withAutoConfiguration(neonCacheAutoConfiguration)
      .withBean<Cache>(RedisCache.new)
      .run((context) {
    expect(context, hasSingleBean<Cache>());
    expect(context.getBean<Cache>(), isA<RedisCache>());
  });
});
```

Keep the starter's third-party constraints wide (`dio: '>=5.0.0 <7.0.0'`) so applications can resolve them together with other starters.

## Starters of the family

| Starter | What adding the dependency gives |
|---|---|
| `spring_boot_starter_logging` | Console output with patterns, log files with rollover, `logging.*` properties, a `LogBuffer` |
| `spring_boot_starter_web` | An HTTP server: `@RestController`, JSON bodies, `@Valid`, `ProblemDetail` errors, SSE, filters, CORS |
| `spring_boot_starter_security` | A security filter chain, HTTP Basic, form login, sessions, CSRF, JWT resource servers |
| `spring_boot_starter_feign` | HTTP clients from annotated interfaces |
| `spring_boot_starter_websocket` | WebSocket clients and endpoints |
| `spring_boot_starter_cache` | `@Cacheable`, `@CachePut`, `@CacheEvict`, a `CacheManager` |
| `spring_boot_starter_scheduling` | `@Scheduled` methods and a `TaskScheduler` |
| `spring_boot_starter_data` | Repositories and SQL databases |
| `spring_boot_starter_actuator` | Health, info, metrics and other management endpoints |
| `spring_boot_starter_flutter` | Flutter apps: `SpringApplicationWidget`, beans in widgets, themes, platform profiles |
| `spring_boot_starter_test` (dev) | `springBootTest`, `ApplicationContextRunner`, bean overrides, `captureLogs` |

## In Spring (Java)

```text
# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.neon.cache.CacheAutoConfiguration
```

```java
@AutoConfiguration(after = JacksonAutoConfiguration.class)
@AutoConfigureOrder(10)
class CacheAutoConfiguration { ... }
```

Differences:

- The module, not the class, is the unit: `order`, `before` and `after` are on `@AutoConfigurationModule`, and classes can be named in them by short name.
- Starters are discovered at build time; a new starter needs a rebuild.
- A `Type` in `exclude` is compared by its simple name.
- `build:` (modules left out of a release) has no Spring counterpart.
- `factories` are the entries of Spring's `META-INF/spring.factories`, which `SpringFactoriesLoader.loadFactories(type, classLoader)` finds on the class path. Dart has no class path to scan, so the generator copies the constants into the generated application.

## See also

- [Conditions](conditions.md)
- [Built-in beans](built-in-beans.md)
- [Versions and compatibility](compatibility.md)
- [The generator: auto-configurations](../spring-core-dart-generator/auto-configurations.md)
- [spring_boot_starter_test](../spring-boot-starter-test/index.md)
