@Autowired

@Autowired() asks the container to inject beans into a field, a setter or a method, or chooses which constructor to call.

Why

Constructor parameters of a bean are injected without any annotation. That is the usual way and needs no @Autowired. Use the annotation in these cases:

What an injection point can receive:

A nullable type makes a dependency optional: it receives null when there is no bean. required: false only matters on constructors; on fields, setters and methods it fails the build.

Example

import 'package:spring_core_dart/spring_core_dart.dart';

abstract interface class PaymentGateway {
  void charge(double amount);
}

abstract interface class DiscountRule {
  double apply(double total);
}

abstract interface class Clock {
  DateTime now();
}

class AuditLog {}

@Service()
class Checkout {
  // A field, set after the constructor ran.
  @Autowired()
  late final PaymentGateway gateway;

  // Every DiscountRule bean, sorted by @Order.
  @Autowired()
  late final List<DiscountRule> rules;

  // Optional: null when no AuditLog bean exists.
  @Autowired()
  AuditLog? audit;

  // A method, called once with injected arguments.
  @Autowired()
  void init(Clock clock) => startedAt = clock.now();

  DateTime? startedAt;

  void pay(double total) {
    var amount = total;
    for (final rule in rules) {
      amount = rule.apply(amount);
    }
    gateway.charge(amount);
  }
}

// Two constructors: the container calls the one with the most
// parameters it can satisfy.
@Service()
class Notifier {
  @Autowired(required: false)
  Notifier() : clock = null;

  @Autowired(required: false)
  Notifier.withClock(Clock this.clock);

  final Clock? clock;
}

Parameters

Name Type Default Meaning
required bool true On a constructor, false makes it one of several candidates. Elsewhere, use a nullable type instead.

In Spring (Java)

@Service
class Checkout {
  @Autowired PaymentGateway gateway;
  @Autowired List<DiscountRule> rules;

  @Autowired
  void init(Clock clock) { startedAt = clock.now(); }
}

Differences that matter:

See also