@Fallback

@Fallback() makes a bean the one used only when no other bean of the type is there.

Why

It is the opposite of @Primary. A @Primary bean wins over the others. A @Fallback bean loses to any other candidate.

Use it for a default implementation that something else may replace: a test profile, an optional module, an application that brings its own. The code that adds the replacement does not need to know about the default or mark itself primary.

Example

import 'package:spring_core_dart/spring_core_dart.dart';

abstract interface class Clock {
  DateTime now();
}

// The normal clock. It steps aside when another Clock exists.
@Component()
@Fallback()
class SystemClock implements Clock {
  @override
  DateTime now() => DateTime.now();
}

// Exists only with the `test` profile, and then wins.
@Component()
@Profile(['test'])
class FixedClock implements Clock {
  @override
  DateTime now() => DateTime(2026, 1, 1);
}

@Service()
class Invoices {
  Invoices(this.clock); // SystemClock, or FixedClock in tests
  final Clock clock;
}

Parameters

None.

In Spring (Java)

Spring 6.2 and later:

@Component
@Fallback
class SystemClock implements Clock { ... }

The meaning is the same.

See also