
# Conditions

A condition decides whether a bean, a `@Bean` method or a whole configuration class is registered at all. `spring_boot_dart` brings Spring Boot's `@ConditionalOn...` annotations. They are what makes auto-configuration back off when the application declares its own bean, and what lets a property switch a feature on or off.

## Why

A starter must offer defaults without forcing them: register a `Cache` only when the application has none, a metrics exporter only when there is a registry, a feature only when a property says so. An application uses the same annotations to choose beans per environment without `if`s in the code.

## Example

```dart
@AutoConfiguration()
class SearchAutoConfiguration {
  // The default index, unless the application declares its own.
  @Bean()
  @ConditionalOnMissingBean(SearchIndex)
  SearchIndex searchIndex() => InMemoryIndex();

  // On unless search.enabled=false.
  @Bean()
  @ConditionalOnBooleanProperty('search.enabled', matchIfMissing: true)
  SearchService searchService(SearchIndex index) => SearchService(index);

  // Only when the application has exactly one DataSource to inject.
  @Bean()
  @ConditionalOnSingleCandidate(DataSource)
  SqlIndexer sqlIndexer(DataSource source) => SqlIndexer(source);

  // Only on Kubernetes.
  @Bean()
  @ConditionalOnCloudPlatform(CloudPlatform.kubernetes)
  ClusterSync clusterSync() => ClusterSync();
}
```

## The conditions

| Annotation | Registers when |
|---|---|
| `@ConditionalOnProperty` | a property is set to anything but `false`, or to `havingValue` |
| `@ConditionalOnBooleanProperty` | a property is `true` (or `havingValue: false`) |
| `@ConditionalOnExpression` | a SpEL expression gives `true` |
| `@ConditionalOnResource` | every listed resource exists |
| `@ConditionalOnCloudPlatform` | the application runs on a platform |
| `@ConditionalOnPrimaryIsolate` | the code runs in the application's first isolate |
| `@ConditionalOnBean` | some beans are already registered |
| `@ConditionalOnMissingBean` | no such bean is registered yet |
| `@ConditionalOnSingleCandidate` | exactly one bean of a type can be injected |

`spring_core_dart` adds `@Profile` and `@Conditional` with your own `Condition` (see [@Conditional](../spring-core-dart/beans/conditional.md)). The actuator adds `@ConditionalOnEnabledHealthIndicator` and `@ConditionalOnEnabledInfoContributor`.

Java's `@ConditionalOnClass` has no counterpart: a Dart program cannot test whether a class exists at run time, and a starter's dependencies are always there.

## @ConditionalOnProperty

| Parameter | Default | Meaning |
|---|---|---|
| `name` (positional) or `.names([...])` | required | The property, or several that must all match |
| `prefix` | `''` | Put before each name; a `.` is added when missing |
| `havingValue` | `null` | The value required, compared ignoring case. `null` or empty: any value except `false` |
| `matchIfMissing` | `false` | Whether a property that is not set matches |

```dart
// Search is on unless feature.search=false.
@Service()
@ConditionalOnProperty('feature.search', matchIfMissing: true)
class SearchService {}

// app.feature.a and app.feature.b must both be "on".
@Bean()
@ConditionalOnProperty.names(['a', 'b'], prefix: 'app.feature', havingValue: 'on')
Feature feature() => Feature();
```

## @ConditionalOnBooleanProperty

The plain way to write an on/off switch. Unlike `@ConditionalOnProperty`, the value is read as a boolean: a value that is not a boolean stops the start instead of counting as "set".

| Parameter | Default | Meaning |
|---|---|---|
| `name` or `.names([...])` | required | The property, or several that must all match |
| `prefix` | `''` | Put before each name |
| `havingValue` | `true` | The value that matches; `false` for a bean that replaces a feature when it is off |
| `matchIfMissing` | `false` | Whether a property that is not set matches |

```dart
// On by default; app.audit.enabled=false turns it off.
@Bean()
@ConditionalOnBooleanProperty('app.audit.enabled', matchIfMissing: true)
Audit audit() => Audit();
```

## @ConditionalOnExpression

A SpEL expression, with or without `#{...}`; `${...}` placeholders are replaced first. It can refer to `environment` and to beans registered so far. A `null` result counts as `false`; any other non-boolean result stops the start. Without an argument it always matches.

```dart
// Only when caching is on (the default) and the shop runs in the EU.
@Bean()
@ConditionalOnExpression(r"${app.cache:true} and '${app.mode}' == 'eu'")
Cache cache() => Cache();
```

## @ConditionalOnResource

Every location must exist. Locations are resolved like any resource (`resources:` is `lib/resources/`, `file:` the file system), after placeholders are replaced.

```dart
// TLS only where the operators mounted a certificate.
@Bean()
@ConditionalOnResource(['file:./config/tls/cert.pem'])
TlsSettings tls() => TlsSettings.fromDirectory('./config/tls');
```

## @ConditionalOnCloudPlatform

`CloudPlatform.kubernetes`, `heroku`, `cloudFoundry`, `azureAppService`, `amazonEcs`, `nomad` or `sap`, detected from environment variables as in Spring Boot, or forced with `spring.main.cloud-platform` (`none` turns detection off). The detection table is on [Profiles](configuration/profiles.md#cloud-platforms).

## @ConditionalOnPrimaryIsolate

Registers a bean only in the application's primary isolate: the first one, which is the only one unless the web server runs a [pool of isolates](../spring-boot-starter-web/server/isolates.md) (`server.isolates.count`).

In a pool every isolate runs the whole application with its own beans. Put the condition on what must exist once for the application and not once per isolate: the bean that polls a queue, sends the nightly report, migrates the data.

```dart
@Component()
@ConditionalOnPrimaryIsolate()
class NightlyReport { /* ... */ }
```

- Without a pool it always matches, so it costs nothing to put it on a bean before the application has a pool.
- **A bean under it does not exist in the other isolates.** A bean that takes it in its constructor fails there, and that isolate does not start. Put the condition on both, or take the dependency as a nullable type.
- A `@RestController` under it is mapped in the first isolate only; a request another isolate takes finds no handler.
- For one step inside a bean that every isolate needs, inject `IsolateInfo` and test `isolate.primary` (see [Isolates](../spring-core-dart/isolates/index.md#isolateinfo)).
- When the other isolates need what the bean knows, make it a `PrimaryIsolateHandler` and ask it with `primaryIsolate.ask(...)` (see [Asking the first isolate](../spring-core-dart/isolates/primary-isolate.md)).
- `@Scheduled` methods need no condition: they run in the first isolate only by default (`spring.task.scheduling.isolates`).

Spring has no counterpart: a JVM's threads share their beans.

## @ConditionalOnBean and @ConditionalOnMissingBean

| Form | Requires (or requires the absence of) |
|---|---|
| `@ConditionalOnBean()` | a bean of the annotated `@Bean` method's return type |
| `@ConditionalOnBean(DataSource)` | a bean of that type |
| `@ConditionalOnBean.named('dataSource')` | a bean of that name |
| `@ConditionalOnBean.where(types: [...], names: [...], annotations: [...], search: ...)` | every one described: one of each type, each name, one carrying each annotation |
| `@ConditionalOnMissingBean.where(..., ignored: [TestClock])` | as above, beans of `ignored` types not counting |

- `@ConditionalOnBean` needs *all* described beans; `@ConditionalOnMissingBean` matches when *none* of them exists.
- `annotations:` matches the exact annotation class, on the bean's class or `@Bean` method; a meta-annotated bean does not count.
- `search:` is a `SearchStrategy`: `all` (this context and its parents, the default), `current` (this context only) or `ancestors` (only the parents).
- Beans declared with `autowireCandidate: false` or `defaultCandidate: false` count for neither, as in Spring Boot 3.4+.

```dart
@AutoConfiguration()
class HttpAutoConfiguration {
  // Not registered when the application has HttpClientSettings.
  @Bean()
  @ConditionalOnMissingBean()
  HttpClientSettings httpSettings() => HttpClientSettings();

  // A TestClock bean does not count as a Clock here.
  @Bean()
  @ConditionalOnMissingBean.where(ignored: [TestClock])
  Clock clock() => SystemClock();
}
```

## @ConditionalOnSingleCandidate

`@ConditionalOnBean` is satisfied by several beans of a type, but injecting one of them would then fail with an ambiguity. `@ConditionalOnSingleCandidate(DataSource)` checks that injection works: one candidate, or one `@Primary()` among several, or one that is not `@Fallback()`.

## When bean conditions are decided

Bean conditions depend on what was registered before them. As with Spring Boot's `OnBeanCondition`, they are decided when the configuration class is read, class by class, in this order:

1. the application's own classes (a scanned `@Component` and an `@Import`ed class count too, at their place);
2. the auto-configurations, in [their order](auto-configuration.md#the-order-of-registration).

By then every earlier class has registered its `@Bean` methods and run its imported `BeanRegistrar` or `ImportBeanDefinitionRegistrar`, so a bean registered in any of those ways counts. That is why bean conditions belong on auto-configuration: there, the application's beans are always seen. On an application class, a component declared before the class whose bean it looks for is decided first, as in Spring.

## On a class

On a configuration class, a condition decides the class, its `@Bean` methods and its imports at once, all or nothing. A skipped class runs no registrar, and what it selects is not registered. A class whose condition looks for the bean its own imported class defines stays registered (Spring Boot's `PooledDataSourceConfiguration` pattern). Its `@PropertySource`s load anyway, because they are read while parsing, as in Spring.

## The condition evaluation report

To see why a bean is there or not, start with `--debug` (or `debug=true`, `DEBUG=true`):

```bash
dart run bin/main.dart --debug
```

The `ConditionEvaluationReport` is logged at INFO after the refresh, or after a failed start. It lists the positive matches (registered, with the conditions that matched) and the negative matches (skipped, with the condition that did not). A configuration class's conditions are listed under its key. `--debug` also sets the framework loggers to debug (see [Logging levels](logging-levels.md)).

## In Spring (Java)

The same names and parameters. Differences:

- `@ConditionalOnBean(annotations: [Service])` matches that exact annotation class, not meta-annotations.
- No `@ConditionalOnClass`, `@ConditionalOnWebApplication` or `@ConditionalOnJava`.
- `@ConditionalOnPrimaryIsolate` is this framework's own.
- The report names each condition and whether it matched, without Spring Boot's detailed messages (`found bean 'x'`).

## See also

- [Auto-configuration and starters](auto-configuration.md)
- [Isolates](../spring-core-dart/isolates/index.md)
- [@Conditional](../spring-core-dart/beans/conditional.md)
- [@Profile](../spring-core-dart/beans/profile.md)
- [Profiles](configuration/profiles.md)
