
# 制御の反転と依存性注入

普通のプログラムでは、各オブジェクトが使うオブジェクトを自分で生成するか、`main` がそれらすべてを手で生成します。Spring では、クラスと、それぞれが必要とするものを宣言するだけです。コンテナがオブジェクトを生成し、それぞれに依存を渡し、設定し、最後に閉じます。生成の制御が自分のコードからコンテナへ移ります。これが **制御の反転** です。オブジェクトに依存を自分で生成させるのではなく、外から渡すことが **依存性注入** です。

## 問題

いつもの書き方で書いた、小さな注文サービスです。

```dart
class OrderService {
  // サービスが使うものを自分で組み立てる。
  final _repository = OrderRepository(Database.open('orders.db'));
  final _payments = CardGateway(apiKey: Platform.environment['CARD_KEY']!);
  final _mailer = Mailer('smtp.example.com');

  Future<void> place(Order order) async {
    await _payments.charge(order.total);
    await _repository.save(order);
    await _mailer.send(order.email, 'Thank you for your order');
  }
}
```

これは動きますが、次の問題があります。

- **テストしにくい。** `place` のテストは本物のカードに課金し、本物のファイルに書き込み、本物のメールを送ります。フェイクを渡す方法がありません。
- **変更しにくい。** 開発中にフェイクのゲートウェイを使うには、クラスに `if` が必要です。別のデータベースを使うには、クラスを編集しなければなりません。
- **設定が散らばっている。** ファイル名、キー、メールのホストが、三つの場所でそれぞれ独自の方法で読まれています。
- **結び付けが繰り返される。** `Mailer` を必要とするすべてのクラスが、独自の設定で独自のものを生成します。
- **規模が大きくなると破綻する。** 新しい機能はすべて既存のクラスに入り込みます。二つ目の支払い方法、注文後のロイヤルティボーナス、すべての課金の前後のログ行は、どれも `OrderService` の編集を意味します。何十ものサービスがあると、すべての変更がすでに動いているコードに触れ、クラスは誰も変更しようとしない絡まりへと育っていきます。
- **SOLID に反する。** 大きなコードベースを健全に保つ原則は、各クラスが自分の依存を組み立てると従いにくくなります。以下で、それぞれを小さな例で示します。

生成を `main` に移せばテストの問題は解決しますが、`main` はクラスが増えるたびに大きくなり、それらを正しい順序で生成しなければならず、コンストラクターのパラメーターが新しく増えるたびに、`main` と、そのクラスを組み立てるすべてのテストを編集することになります。

### SOLID を一つずつ

各原則を数行で示します。まずいつもの書き方、次に Spring での書き方です。

**S: 単一責任。** クラスが変更される理由は一つであるべきです。

```dart
// 以前: 注文を受けることと、メールサーバーを選んで設定することの両方。
class OrderService {
  final _mailer = Mailer(host: 'smtp.example.com', port: 587);
}

// Spring では: サービスは Mailer を使うだけ。どれを使い、どう設定するかは
// Mailer Bean の仕事。
@Service()
class OrderService {
  OrderService(this.mailer);
  final Mailer mailer;
}
```

**O: 拡張に開かれ、修正に閉じている。** 新しい振る舞いは、動いているコードの編集ではなく、新しいコードから来るべきです。

```dart
// 以前: 注文への新しい反応は、すべて place() の新しい行になる。
Future<void> place(Purchase purchase) async {
  await repository.save(purchase);
  await mailer.sendReceipt(purchase);
  await points.add(purchase.customer, 10); // ボーナスのために書き足した
}

// Spring では: 新しい反応は新しいクラス。place() は決して変わらない。
@Component()
class LoyaltyBonus implements PurchaseListener {
  @override
  Future<void> onPlaced(Purchase purchase) async { /* ポイントを加える */ }
}
```

`OrderService` は `List<PurchaseListener>` を求め、すべての実装を受け取ります。[自ら拡張するパターン](None#自ら拡張するパターン) を参照してください。

**L: リスコフの置換。** インターフェースのどの実装も、そのインターフェースが期待される場所で動かなければなりません。

```dart
// 以前: 呼び出し側が具象型をチェックするので、新しいゲートウェイがそれを壊す。
if (gateway is CardGateway) { gateway.charge(total); } else { /* ... */ }

// Spring では: 呼び出し側は PaymentGateway しか知らない。dev プロファイルの
// フェイクと本物は入れ替え可能。
@Component()
@Profile(['dev'])
class FakeGateway implements PaymentGateway {
  @override
  Future<void> charge(double amount) async {}
}
```

**I: インターフェース分離。** 大きなクラスではなく、使う小さなインターフェースに依存します。

```dart
// 以前: レポートはクエリを一つ必要とするだけなのに、リポジトリ全体に依存する。
class SalesReport {
  SalesReport(this.repository); // OrderRepository: 30 個のメソッド
  final OrderRepository repository;
}

// Spring では: 狭いインターフェースを求める。それを実装するリポジトリの
// Bean が注入される。
abstract interface class SalesTotals {
  Future<double> totalFor(DateTime month);
}

@Service()
class SalesReport {
  SalesReport(this.totals);
  final SalesTotals totals;
}
```

**D: 依存性逆転。** 抽象に依存し、具象クラスは別の何かに選ばせます。

```dart
// 以前: サービスは一つのゲートウェイと一つのデータベースファイルに溶接されている。
class OrderService {
  final _payments = CardGateway(apiKey: Platform.environment['CARD_KEY']!);
  final _repository = OrderRepository(Database.open('orders.db'));
}

// Spring では: サービスはインターフェースを指定する。コンテナが実装を選ぶ
// (プロファイル、@Primary、テストのオーバーライドなどで)。
@Service()
class OrderService {
  OrderService(this.payments, this.repository);
  final PaymentGateway payments;
  final OrderRepository repository;
}
```

五つすべてに手作業で従うこともできますが、その場合すべてのクラスにファクトリーが必要になり、ファクトリーにも独自の結び付けが必要になります。コンテナがその結び付けを行うので、正しい設計が簡単な設計になります。

## 考え方

Spring では、クラスは必要なものをコンストラクターで宣言し、アノテーションがそれを管理するようコンテナに伝えます。

```dart
@Service()
class OrderService {
  OrderService(this._repository, this._payments, this._mailer);

  final OrderRepository _repository;
  final PaymentGateway _payments;
  final Mailer _mailer;

  Future<void> place(Order order) async {
    await _payments.charge(order.total);
    await _repository.save(order);
    await _mailer.send(order.email, 'Thank you for your order');
  }
}
```

コンテナが管理するオブジェクトが **Bean** です。コンテナは **アプリケーションコンテキスト** です。アプリケーションが起動すると、コンテキストは次のことを行います。

1. すべての Bean クラスを見つけます (ジェネレーターがビルド時にそれらを列挙します)。
2. 順序を決めます。`OrderService` は `OrderRepository`、`PaymentGateway`、`Mailer` を必要とするので、それらが先です。
3. 各 Bean を一度だけ生成し、その型を求めるすべてのコンストラクターに渡します。
4. まずグラフ全体をチェックします。足りない Bean、一つのパラメーターに対する二つの候補、循環があると、レポートとともに起動が止まります。

```text
***************************
APPLICATION FAILED TO START
***************************

Description:

Bean 'orderService' required a bean of type Mailer that could not be found (while creating orderService).

Action:

Declare a bean of that type (a @Component class or a @Bean method), check its @Profile / conditions, or make the injection point nullable.
```

`OrderService` は、もはや協力者がどこから来るかを知りません。それは同じ普通のクラスです。テストは引き続き `OrderService(fakeRepository, fakePayments, fakeMailer)` を呼べます。

## Bean を宣言する

クラスに付けたアノテーションがそれを Bean にします。

| アノテーション | 用途 |
|---|---|
| `@Component()` | 任意の Bean |
| `@Service()` | サービス: ビジネスロジック |
| `@Repository()` | データアクセス |
| `@Controller()`、`@RestController()` | Web のコントローラー (Web スターターとともに) |
| `@Configuration()` | `@Bean()` メソッドが Bean を生成するクラス |

`@Service()`、`@Repository()`、`@Controller()` は `@Component()` と同じように振る舞います。名前は役割を示すだけです。Bean はデフォルトで **シングルトン** です。アプリケーション全体でインスタンスは一つで、起動時に生成されて共有されます。

```dart
@Repository()
class OrderRepository {
  OrderRepository(this._database);

  final Database _database;

  Future<void> save(Order order) => _database.insert('orders', order.toRow());
}
```

詳しくは: [@Component](../components/spring-core-dart/beans/component.md)、[@Service](../components/spring-core-dart/beans/service.md)、[@Repository](../components/spring-core-dart/beans/repository.md)、[コンテナと Bean](../components/spring-core-dart/beans/index.md)。

## コンストラクター注入

コンテナは、各コンストラクターのパラメーターをその型で埋めます。

```dart
@Service()
class CheckoutService {
  CheckoutService(
    this.orders,                  // 一つの OrderService Bean
    this.listeners,               // すべての OrderListener Bean、@Order の順
    this.coupons,                 // nullable: CouponService Bean がなければ null
  );

  final OrderService orders;
  final List<OrderListener> listeners;
  final CouponService? coupons;
}
```

- **`List<T>`** のパラメーターは、型 `T` のすべての Bean を受け取ります。
- **nullable** なパラメーターは省略可能です。
- **`ObjectProvider<T>`** のパラメーターは、Bean を後で受け取るか、まったく受け取りません ([ObjectProvider](../components/spring-core-dart/beans/object-provider.md) を参照)。
- パラメーターに付けた **`@Lazy()`** は、使われるときに Bean を検索する生成されたプロキシを注入し、循環も断ち切ります ([@Lazy](../components/spring-core-dart/beans/lazy.md) を参照)。

コンストラクター注入が推奨される形です。フィールドを `final` にでき、テストでクラスを手で組み立てられます。`late` フィールドに `@Autowired()` を付けるフィールド注入もあります ([@Autowired](../components/spring-core-dart/beans/autowired.md) を参照)。

## インターフェースと複数の実装

クラスではなくインターフェースに依存することで、入れ替えが簡単になります。複数の Bean がそれを実装している場合は、どれを使うかをコンテナに伝えます。

```dart
abstract interface class PaymentGateway {
  Future<void> charge(double amount);
}

// 本物のゲートウェイ。dev 以外のすべてのプロファイルで。
@Component()
@Profile(['!dev'])
class CardGateway implements PaymentGateway {
  CardGateway(@Value(r'${payments.card.key}') this._key);

  final String _key;

  @override
  Future<void> charge(double amount) async {/* _key でカード会社を呼ぶ */}
}

// 開発用のフェイク: 何も課金しない。
@Component()
@Profile(['dev'])
class FakeGateway implements PaymentGateway {
  @override
  Future<void> charge(double amount) async {}
}
```

`--spring.profiles.active=dev` (または `SPRING_PROFILES_ACTIVE=dev`) では、`OrderService` はフェイクを受け取ります。それ以外では本物です。サービスは変わりません。

両方の Bean が同時に存在する場合は、選びます。

| 手段 | 効果 |
|---|---|
| Bean に付けた `@Primary()` | その型の Bean が一つ求められたとき、それが選ばれる。 |
| Bean に付けた `@Fallback()` | 他に候補がない場合にだけ使われる。 |
| Bean とパラメーターに付けた `@Qualifier('name')` | パラメーターはその修飾子を持つ Bean を受け取る。 |
| パラメーターの名前 | Bean 名と一致すれば、その Bean が選ばれる。 |

```dart
@Component()
@Primary()
class EmailNotifier implements Notifier { /* ... */ }

@Component()
@Qualifier('sms')
class SmsNotifier implements Notifier { /* ... */ }

@Service()
class Alerts {
  Alerts(this.notifier, @Qualifier('sms') this.urgent);

  final Notifier notifier; // EmailNotifier、プライマリーのもの
  final Notifier urgent;   // SmsNotifier
}
```

詳しくは: [@Primary](../components/spring-core-dart/beans/primary.md)、[@Qualifier](../components/spring-core-dart/beans/qualifier.md)、[@Fallback](../components/spring-core-dart/beans/fallback.md)、[@Profile](../components/spring-core-dart/beans/profile.md)。

## 自ら拡張するパターン

コンテナがあれば、古典的なデザインパターンに登録のコードは不要です。クラスを追加すれば、コンテナがそれを見つけます。すでに動いているものは何も編集されません。これが実践における開放閉鎖原則です。

### Observer: すべての実装が拾われる

サービスが起きたことを知らせ、任意の数のリスナーが反応します。インターフェースの `List` を求めれば、コンテナはそれを実装するすべての Bean を渡します。他より先に実行すべきリスナーは、`@Order` アノテーションでその位置を宣言します (小さい値が先)。

```dart
abstract interface class OrderListener {
  Future<void> onPlaced(Order order);
}

@Service()
class OrderService {
  OrderService(this.repository, this.listeners);

  final OrderRepository repository;
  final List<OrderListener> listeners; // すべての OrderListener Bean

  Future<void> place(Order order) async {
    await repository.save(order);
    for (final listener in listeners) {
      await listener.onPlaced(order);
    }
  }
}

@Component()
class ConfirmationMail implements OrderListener {
  ConfirmationMail(this.mailer);

  final Mailer mailer;

  @override
  Future<void> onPlaced(Order order) =>
      mailer.send(order.email, 'Thank you for your order');
}
```

一か月後のロイヤルティボーナスは、新しいファイル一つです。`OrderService` と `ConfirmationMail` には触れません。

```dart
@Component()
class LoyaltyBonus implements OrderListener {
  LoyaltyBonus(this.points);

  final PointsService points;

  @override
  Future<void> onPlaced(Order order) => points.add(order.customer, 10);
}
```

一部のプロファイル専用 (`@Profile(['prod'])`) や設定の背後 (`@ConditionalOnProperty`) のリスナーも、ただのクラスです。その条件が偽の場所では、リストに含まれません。

より疎な結合にするには、代わりにイベントを発行します。発行する側はインターフェースすら知りません。`@EventListener()` を付けた任意の Bean のメソッドは、そのパラメーターの型のイベントを受け取ります。

```dart
class OrderPlaced {
  const OrderPlaced(this.order);
  final Order order;
}

@Service()
class OrderService {
  OrderService(this.repository, this.events);

  final OrderRepository repository;
  final ApplicationEventPublisher events;

  Future<void> place(Order order) async {
    await repository.save(order);
    events.publishEvent(OrderPlaced(order));
  }
}

@Component()
class SalesReport {
  @EventListener()
  void onPlaced(OrderPlaced event) { /* 売上を数える */ }
}
```

詳しくは: [@EventListener](../components/spring-core-dart/events/event-listener.md)、[イベント](../components/spring-core-dart/events/index.md)。

### Decorator: Bean の周りに加えられる振る舞い

デコレーターはオブジェクトを包み、それを変えずに振る舞いを加えます。コンテナがあれば、包むことは一度宣言するだけで、インターフェースを求めるすべてのクラスがデコレートされたオブジェクトを受け取ります。

**一つのインターフェースに一つのデコレーター。** デコレーターに `@Primary` を付けて誰もが受け取る Bean にし、本物はその修飾子で求めさせます。

```dart
@Component()
@Qualifier('card')
class CardGateway implements PaymentGateway { /* カードに課金する */ }

// 失敗した課金を最大三回まで再試行する。
@Component()
@Primary()
class RetryingGateway implements PaymentGateway {
  RetryingGateway(@Qualifier('card') this._inner);

  final PaymentGateway _inner;

  @override
  Future<void> charge(double amount) async {
    for (var attempt = 1; ; attempt++) {
      try {
        return await _inner.charge(amount);
      } on Exception {
        if (attempt == 3) rethrow;
      }
    }
  }
}
```

`OrderService` は引き続き `PaymentGateway` を求め、今は再試行するものを受け取ります。再試行を取り除くには、クラスを一つ削除するだけです。

**多くのクラスに一つの振る舞い。** 計測、ロギング、キャッシュ、トランザクションのように、同じものが多くのメソッドを包むべき場合は、アスペクトがデコレーターです。一度書かれ、ルールによって適用されます。ここでは `@Timed()` を付けたすべてのメソッドにです。

```dart
class Timed {
  const Timed();
}

@Aspect()
@Component()
class TimingAspect {
  @Around('@annotation(Timed)')
  Object? time(ProceedingJoinPoint call) {
    final watch = Stopwatch()..start();
    try {
      return call.proceed(); // 本物のメソッド
    } finally {
      const SpringLog('timing')
          .info('${call.signature.name}: ${watch.elapsedMilliseconds} ms');
    }
  }
}

@Service()
class ReportService {
  @Timed()
  Report monthly() { /* ... */ }
}
```

アスペクトを実行するプロキシクラスはジェネレーターがビルド時に書き出します。`ReportService` 自身は計測のコードを含みません。キャッシュとデータのスターターも同じように動きます。`@Cacheable` と `@Transactional` は、スターターが持ち込むアスペクトです。

詳しくは: [AOP](../components/spring-core-dart/aop/index.md)、[@Around とその他のアドバイス](../components/spring-core-dart/aop/advice.md)。

## `@Bean` メソッド

自分のクラスではないオブジェクトもあります。`dart:math` の `Random`、別のパッケージのクライアント、組み立てるのに数行必要なオブジェクトです。それらは `@Configuration()` クラスの `@Bean()` メソッドで生成します。メソッドのパラメーターはコンストラクターのものと同じように注入されます。

```dart
@Configuration()
class InfrastructureConfig {
  @Bean()
  Random random() => Random.secure();

  @Bean()
  Database database(@Value(r'${orders.db:orders.db}') String path) =>
      Database.open(path);

  // Mailer は close() メソッドを持つ: コンテキストが閉じるときにコンテナがそれを呼ぶ。
  @Bean()
  Mailer mailer(MailProperties properties) =>
      Mailer(properties.host, port: properties.port);
}
```

Bean の名前はメソッドの名前 (`random`、`database`、`mailer`) です。詳しくは: [@Bean](../components/spring-core-dart/beans/bean.md)、[@Configuration](../components/spring-core-dart/beans/configuration.md)。

## 設定値

設定値は `lib/resources/application.properties` または `application.yml` に置き、その上にプロファイルごとのファイル (`application-prod.yml`) を重ねます。環境変数とコマンドライン引数はファイルを上書きするので、同じビルドがどこでも動きます。

```yaml
# lib/resources/application.yml
mail:
  host: smtp.example.com
  port: 587
orders:
  limit: 50
```

一つの値は `@Value` でパラメーターに入ります。

```dart
@Service()
class OrderLimits {
  // ファイルからは 50。キーがなければ 100。
  OrderLimits(@Value(r'${orders.limit:100}') this.limit);

  final int limit;
}
```

値のグループは `@ConfigurationProperties` で型付きのクラスに入ります。そのクラスは Bean で、プレフィックスの下のすべてのキーからバインドされ、フィールドの型に変換され、`@Validated()` があれば起動時にチェックされます。

```dart
@ConfigurationProperties('mail')
@Validated()
class MailProperties {
  /// The SMTP server.
  @NotBlank()
  String host = 'localhost';

  @Min(1)
  int port = 25;

  Duration timeout = const Duration(seconds: 10); // mail.timeout=30s
}
```

`port` は `mail.port`、`--mail.port=2525`、`MAIL_PORT=2525` からバインドされます。不正な値は、キー、値、違反したルールとともに起動を止めます。詳しくは: [設定](../components/spring-core-dart/config/index.md)、[@Value](../components/spring-core-dart/config/value.md)、[@ConfigurationProperties](../components/spring-core-dart/config/configuration-properties.md)、[プロファイル](../components/spring-core-dart/config/profiles.md)。

## ライフサイクル

コンテナは Bean を生成し、閉じもします。Bean は両端でコードを実行できます。

```dart
@Component()
class PriceCache {
  PriceCache(this._source);

  final PriceSource _source;
  final _prices = <String, double>{};

  // コンストラクターと注入の後、誰かが Bean を使う前。
  @PostConstruct()
  void warmUp() => _prices.addAll(_source.defaults());

  // コンテキストが閉じるとき: シャットダウン時、またはテストの終わり。
  @PreDestroy()
  void clear() => _prices.clear();
}
```

アプリケーションとともに開始・停止するバックグラウンドの作業 (ポーラー、ソケット) には、`Lifecycle` または `SmartLifecycle` を実装します。詳しくは: [@PostConstruct](../components/spring-core-dart/beans/post-construct.md)、[@PreDestroy](../components/spring-core-dart/beans/pre-destroy.md)、[Lifecycle と SmartLifecycle](../components/spring-core-dart/beans/lifecycle.md)。

## スコープ

ほとんどの Bean にはシングルトンが適しています。`@Scope` は、いくつのインスタンスが存在するかを変えます。

| スコープ | インスタンス |
|---|---|
| singleton (デフォルト) | コンテキスト全体で一つ |
| `ScopeType.prototype` | 注入と検索のたびに新しいもの |
| 独自のスコープ | 自分で定義する区間ごとに一つ: 画面、セッション、ジョブ。たとえば Flutter のナビゲーションのスターターは、ルートごとのスコープを登録します。 |

```dart
// カートの利用者はそれぞれ独自のインスタンスを受け取る。
@Component()
@Scope(ScopeType.prototype)
class ShoppingCart {
  final items = <String>[];
}
```

詳しくは: [@Scope](../components/spring-core-dart/beans/scope.md)。

## テスト

Bean は依存を受け取るので、どちらのレベルでもテストは簡単です。

**ユニットテスト** は、フェイクを使ってクラスを手で組み立てます。

```dart
test('a placed order is charged and saved', () async {
  final payments = RecordingGateway();
  final service = OrderService(InMemoryOrders(), payments, SilentMailer());

  await service.place(Order(total: 12.5, email: 'ada@example.com'));

  expect(payments.charged, [12.5]);
});
```

**アプリケーションのテスト** は、テストのプロパティとプロファイルで本物のアプリケーションを起動し、指定した Bean だけを置き換えます。`springBootTest` は `spring_boot_starter_test` のものです。

```dart
import 'package:spring_boot_starter_test/spring_boot_starter_test.dart';
import 'package:test/test.dart';

import '../bin/spring_gen/main.spring.dart'; // 生成された springApplication

void main() {
  final payments = RecordingGateway();

  final app = springBootTest(
    springApplication,
    profiles: ['test'],                            // application-test.properties を読む
    properties: {'orders.limit': '3'},
    overrides: [BeanOverride<PaymentGateway>(payments)],
  );

  test('the checkout uses the fake gateway', () async {
    await app.getBean<OrderService>().place(Order(total: 5, email: 'a@b.c'));
    expect(payments.charged, [5]);
  });
}
```

`PaymentGateway` を求めるすべての Bean はフェイクを受け取り、アプリケーションの残りは本物です。詳しくは: [テスト: @SpringBootTest と @DataTest](../components/spring-core-dart-generator/tests.md)。

## Spring Boot なしで

コンテナは単独でも動きます。`@ComponentScan()` 変数はそのディレクトリの Bean を集め、コンテキストは自分で起動します。

```dart
// lib/src/beans.dart
import 'package:spring_core_dart/spring_core_dart.dart';
import 'package:my_app/spring_gen/src/beans.spring.dart'; // ジェネレーターが書き出す

@ComponentScan()
final BeanModule appBeans = $appBeans;
```

```dart
void main() {
  final context = ApplicationContext.run([appBeans]);
  context.getBean<OrderService>();
  context.close();
}
```

`@SpringBootApplication()` はこれを代わりに行い、設定ファイル、スターター、起動時のレポートを加えます。詳しくは: [@ComponentScan](../components/spring-core-dart/beans/component-scan.md)、[ApplicationContext](../components/spring-core-dart/beans/application-context.md)。

## Spring (Java) との対応

モデルは Spring のもので、名前も同じです。`@Component`、`@Service`、`@Bean`、`@Primary`、`@Qualifier`、`@Value`、`@ConfigurationProperties`、`@PostConstruct`、`@Scope` です。ここで重要な違い:

- Bean は、起動時のクラスパスのスキャンではなく、ビルド時にジェネレーターが見つけます。
- Bean の循環は常にエラーです。パラメーターに付けた `@Lazy()` や `ObjectProvider` で断ち切ってください。
- プレースホルダーは raw 文字列で書きます: `@Value(r'${key}')`。

## 関連項目

- [比較](../compare/index.md): get_it、Observer、メソッドの周りのロジック、HTTP クライアントを並べて比較
- [コンテナと Bean](../components/spring-core-dart/beans/index.md)
- [設定](../components/spring-core-dart/config/index.md)
- [条件](../components/spring-core-dart/beans/conditional.md)
