
# One context for all starters

An application built with Spring for Dart has one **application context**. It holds your beans and the beans of every starter you depend on, and one `Environment` holds all the properties. So the starters work together without any code of yours: the web starter writes JSON with the core's `ObjectMapper`, the security starter puts its filter in front of the web starter's controllers, the cache starter's advice wraps your services. And your own bean of a type replaces the starter's.

## How starters are found

A starter ships its beans in a file of fixed name, `lib/spring_auto_configuration.dart`. In it, a top-level `BeanModule` variable carries `@AutoConfigurationModule()`. This is the web starter's:

```dart
// spring_boot_starter_web/lib/spring_auto_configuration.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:spring_boot_starter_web/src/config/config.dart';
import 'package:spring_boot_starter_web/src/web_auto_configuration.dart';

export 'package:spring_boot_starter_logging/spring_auto_configuration.dart';

@AutoConfigurationModule()
final BeanModule springBootStarterWebAutoConfiguration = BeanModule(
  'springBootStarterWebAutoConfiguration',
  [...webMvcAutoConfiguration], // the server, the router, the filters, ...
  imports: [webConfigBeans],    // the server.* and spring.mvc.* properties
);
```

When you run `dart run build_runner build` for an application with `@SpringBootApplication()`, the generator:

1. walks the application's dependencies in `pubspec.yaml`, direct and transitive;
2. reads `lib/spring_auto_configuration.dart` of each package that has one;
3. takes every variable annotated `@AutoConfigurationModule`, checks the versions it `requires`, and decides its `build` condition if it has one;
4. writes them into the generated `springApplication`.

```dart
// bin/spring_gen/main.spring.dart (generated, simplified)
SpringApplication get springApplication => SpringApplication(
  [$application],                           // your beans
  autoConfigurations: [
    springBootAutoConfiguration,            // spring_boot_dart
    springBootStarterLoggingAutoConfiguration,
    springBootStarterWebAutoConfiguration,
  ],
);
```

This is the Dart version of Spring Boot's `META-INF/spring/...AutoConfiguration.imports` files. Spring Boot reads them from the class path when the application starts; here the generator reads them at build time. So after adding a starter to `pubspec.yaml`, run `build_runner` again. More: [Auto-configurations](../components/spring-core-dart-generator/auto-configurations.md).

## The order of registration

At every start, `SpringApplication` registers:

1. **your beans first**;
2. **then the auto-configuration modules**, sorted as Spring Boot's `AutoConfigurationSorter` does: by `order` (`0` by default), then by name, then moved by `before` and `after`.

The order matters for conditions. A starter's bean marked "only when there is none" is decided after your beans are registered, so it sees yours and steps aside. Between starters, `after` says whose beans must be registered first; the actuator starter's module, for example, is declared `after: ['springBootStarterWebAutoConfiguration']`. A cycle among `before` and `after` stops the start.

## One context, shared

Every bean, yours or a starter's, is in the same context and can be injected anywhere. Real examples from the starters:

| Starter | Uses | How |
|---|---|---|
| `spring_boot_starter_web` | The `ObjectMapper` of `spring_boot_dart` | Request and response bodies are read and written with the application's one `ObjectMapper` bean. |
| `spring_boot_starter_feign` | The same `ObjectMapper` | Feign clients encode and decode JSON with it too, so a client and a controller agree on the format. |
| `spring_boot_starter_security` | The web starter's filters | Its filter chain is a `WebFilter` bean (order `-100`, from `spring.security.filter.order`); the web starter runs every `WebFilter` bean before the controllers. |
| `spring_boot_starter_oauth2_client` | Feign's interceptors | With `spring.feign.oauth2.enabled=true` it registers an `OAuth2AccessTokenInterceptor`, a `RequestInterceptor` bean; Feign applies the `RequestInterceptor` beans to its calls, so each one carries the token. |
| `spring_boot_starter_cache`, `spring_boot_starter_data` | Your beans | `cacheAdvisor` and `transactionAdvisor` are AOP advisor beans. They apply `@Cacheable` and `@Transactional` to the methods of your beans, through the proxies the generator writes. |
| `spring_boot_starter_actuator` | Your beans, other starters' beans | Every `HealthIndicator` bean is part of `/actuator/health`: yours, and the data starter's `db` indicator. |
| `spring_boot_starter_flutter` | The logging starter's `LogBuffer` | The debug panel's log section shows the lines kept in the `LogBuffer` bean. |
| `spring_boot_starter_logging` | Everyone | Every package logs through `SpringLog`; the logging starter decides where the lines go and at which level. |

Your beans take part the same way. A `WebFilter` of yours runs in the same chain as the security filter, ordered by `@Order`:

```dart
// Runs after the security filter (-100): only for requests it let through.
@Component()
@Order(0)
class AuditFilter implements WebFilter {
  AuditFilter(this.audit);

  final AuditLog audit; // a bean of yours

  @override
  Future<void> doFilter(
    ServerHttpRequest request,
    ServerHttpResponse response,
    WebFilterChain chain,
  ) {
    audit.record('${request.method.value} ${request.path}');
    return chain.doFilter(request, response);
  }
}
```

And a `HealthIndicator` of yours appears in the actuator's report without registration:

```dart
@Component()
class OrdersHealthIndicator extends HealthIndicator {
  OrdersHealthIndicator(this.orders);

  final Orders orders;

  @override
  Future<Health> health() async => await orders.reachable()
      ? Health.up().withDetail('pending', await orders.pending()).build()
      : Health.down().build();
}
```

## Conditions

A starter's bean definition carries conditions that decide, at startup, whether it is registered at all:

| Condition | Registers when |
|---|---|
| `@ConditionalOnMissingBean` | no bean of the type (or name) exists yet. This is how your bean replaces a starter's. |
| `@ConditionalOnBean` | a bean of the type (or name) exists |
| `@ConditionalOnSingleCandidate` | exactly one bean of the type exists, or one is primary |
| `@ConditionalOnProperty` | a property has a value (`havingValue:`, `matchIfMissing:`) |
| `@ConditionalOnBooleanProperty` | a property is `true` |
| `@ConditionalOnExpression` | a SpEL expression is true |
| `@ConditionalOnResource` | a resource exists |
| `@ConditionalOnCloudPlatform` | the application runs on a platform such as Kubernetes |
| `@Profile([...])` | the active profiles match |
| `@Conditional(...)` | your own `Condition` says so |

From the starters:

- The web starter's `webServerFactory` has `ConditionalOnMissingBean(WebServerFactory)`, its `multipartResolver` `ConditionalOnMissingBean(MultipartResolver)`.
- `spring_boot_dart`'s `ObjectMapper` has `ConditionalOnMissingBean(ObjectMapper)`; the cache starter's `cacheManager` `ConditionalOnMissingBean(CacheManager)`.
- The logging starter is on unless `logging.enabled=false`; the scheduling starter unless `spring.task.scheduling.enabled=false` (`ConditionalOnProperty(..., matchIfMissing: true)`).
- The security starter's `defaultSecurityFilterChain` (every request needs a login) is registered only when the application declares no `SecurityFilterChain`.

There is no `@ConditionalOnClass`. In Java it asks whether a library is on the class path; in Dart the dependency graph is known at build time, so the generator decides instead. A starter's module is in the application only when the starter is a dependency, and a module can be left out of the build by a property (see [Modules left out of the build](../components/spring-core-dart-generator/optimizations/build-conditions.md)). The data starter works the same way for databases: the generator writes a `JdbcDriver` bean for each driver package the application depends on (`sqlite3`, `postgres`), and none otherwise.

To see why a bean is there or not, start with `--debug` (or `debug=true`): the condition evaluation report lists the conditions that matched and those that did not. More: [@Conditional](../components/spring-core-dart/beans/conditional.md).

## Replacing a starter's bean

Declare a bean of the same type. The starter's `@ConditionalOnMissingBean` sees yours and backs off:

```dart
@Configuration()
class CacheSetup {
  // The cache starter's own CacheManager is not created.
  @Bean()
  CacheManager cacheManager() => InMemoryCacheManager(
    cacheNames: ['books', 'prices'],
    defaultSpec: const CacheSpec(timeToLive: Duration(minutes: 10)),
  );
}
```

Replacing a bean replaces its configuration too: the `spring.cache.*` properties no longer apply to your `CacheManager`. To change one detail and keep the rest, many starters offer a customizer bean instead. For JSON:

```dart
@Configuration()
class JsonConfig {
  // Pretty JSON, for the web starter's answers and for Feign alike.
  @Bean()
  JsonMapperBuilderCustomizer indented() => JsonMapperBuilderCustomizer.of(
    (builder) => builder.enable(SerializationFeature.indentOutput),
  );
}
```

## Excluding an auto-configuration

When you want none of a starter's beans, exclude its module before its conditions run:

```dart
@SpringBootApplication(
  // A whole module, by its name.
  excludeName: ['springBootStarterCacheAutoConfiguration'],
)
void main(List<String> args) => runApplication(args);
```

- `excludeName` takes the name of a module (the name of its `BeanModule`) or of an auto-configuration class (`JacksonAutoConfiguration`, or its full name). An unknown name is ignored.
- `exclude` takes `@AutoConfiguration` classes by type, for starters written with them (see [Your own starter](your-own-starter.md)). A type that is not an auto-configuration stops the start.
- The property `spring.autoconfigure.exclude` adds to both: `spring.autoconfigure.exclude=JacksonAutoConfiguration`.

An exclusion works at startup: the module's code is still compiled into the application. More: [exclude and excludeName](../components/spring-core-dart-generator/spring-boot-application.md).

## One Environment

All properties are in one `Environment`, read from the same sources for everyone: `application.properties` or `application.yml` and their profile files, files in the working directory or its `config/` folder, environment variables, command-line arguments. A starter's `@ConfigurationProperties` class is bound from it the same way as yours, so every key can be set in each of those places:

```yaml
# lib/resources/application.yml
server:
  port: 9000                         # the web starter
spring:
  json:
    property-naming-strategy: SNAKE_CASE   # spring_boot_dart's ObjectMapper
  cache:
    type: simple                     # the cache starter
logging:
  level:
    root: info                       # the logging starter
    spring.web: debug
shop:
  delivery-time: 2d                  # your own @ConfigurationProperties('shop')
```

Because the web starter and Feign share the `ObjectMapper`, the one line `spring.json.property-naming-strategy: SNAKE_CASE` changes the JSON of your controllers and of your Feign clients together.

The active profiles are shared too: `--spring.profiles.active=prod` reads `application-prod.yml` for every starter, and switches `@Profile(['prod'])` beans of your code. More: [Environment](../components/spring-core-dart/config/environment.md), [Profiles](../components/spring-core-dart/config/profiles.md).

## In Spring (Java)

The model is Spring Boot's: one context, auto-configuration after the application's beans, `@ConditionalOnMissingBean` back-offs, `exclude` and `excludeName`, one `Environment`. Differences that matter:

- Starters are found at build time, from `lib/spring_auto_configuration.dart`, not from the class path at startup. Rebuild after adding one.
- The unit of ordering is the module: `order`, `before` and `after` are arguments of `@AutoConfigurationModule`, not `@AutoConfigureOrder` and `@AutoConfiguration(before:, after:)` on classes.
- A `Type` in `exclude` is compared by its simple name.
- There is no `@ConditionalOnClass`: the dependency graph and build conditions do its job.

## See also

- [The starters](starters.md)
- [Your own starter](your-own-starter.md)
- [Auto-configurations](../components/spring-core-dart-generator/auto-configurations.md)
- [BeanModule](../components/spring-core-dart/beans/bean-module.md)
