
# spring_boot_dart

`spring_boot_dart` は、Spring for Dart のうちアプリケーションを起動する部分です。Spring Boot の `SpringApplication`、その外部設定、`@ConfigurationProperties` のバインド、そして自動構成を Dart に移植したものです。

[spring_core_dart](../spring-core-dart/index.md) だけでも Bean のコンテナは手に入りますが、起動処理は自分で書くことになります。設定ファイルを読み、コンテキストを生成し、ログレベルを設定し、起動時の処理を実行します。`spring_boot_dart` は、`main` に付けた一つのアノテーションでそのすべてを行います。

## 使う理由

どのアプリケーションにも同じ起動コードが必要で、しかも間違えやすいものです。

- ファイル、環境変数、コマンドライン、`--dart-define` からの設定。`dev` や `prod` のようなプロファイル。どのソースが優先されるかについての明確なルール。
- 自分のパッケージの Bean と、依存するライブラリ (「スターター」) の Bean。自分の Bean は常にスターターのものより優先されます。
- 設定のグループを型付きのクラスにバインドし、Bean が使う前に変換と検証を行うこと。
- 起動時のタスクを順に実行し、各段階でイベントを発行し、きれいにシャットダウンすること。
- 起動できないときに、スタックトレースではなく読みやすいレポートを出すこと。

`spring_boot_dart` は、これらすべてを Spring Boot の名前とルールで提供します。そのため、Spring プロジェクトの設定や習慣をそのまま持ち込めます。サーバーでも、コマンドラインツールでも、Flutter アプリでも、Dart VM、AOT ビルド、Web のいずれでも同じように動きます。

## セットアップ

```yaml
# pubspec.yaml
dependencies:
  spring_boot_dart: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # 必須: パッケージをスキャンする
```

`spring_boot_dart` は `spring_core_dart` をエクスポートするため、インポートは一つで足ります。それ以外には何にも依存しません。ほとんどのアプリケーションはこれを直接追加しません。すべてのスターター (`spring_boot_starter_web`、`spring_boot_starter_flutter`、...) がこれに依存し、エクスポートしているためです。

## 例

型付きの設定、起動時のタスク、プロファイルを持つ完全なアプリケーションです。

```dart
// bin/main.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';

import 'spring_gen/main.spring.dart'; // build_runner が書き出す

// shop.* の下のすべてのキーを、型付きで検証済みの一つのオブジェクトに。
@ConfigurationProperties('shop')
@Validated()
class ShopProperties {
  @NotBlank()
  String name = 'NEON Books';

  Duration deliveryTime = const Duration(days: 3); // shop.delivery-time=2d

  @Min(1)
  int maxBasketSize = 10; // shop.max-basket-size
}

// アプリケーションの起動後に一度実行される。
@Component()
@Log()
class Greeting implements ApplicationRunner {
  Greeting(this.shop);

  final ShopProperties shop;

  @override
  void run(ApplicationArguments args) =>
      log.info('${shop.name} is open, ${shop.maxBasketSize} books per basket');
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
```

```yaml
# lib/resources/application.yml
spring:
  application:
    name: neon-books
shop:
  max-basket-size: 20
logging:
  level:
    root: info
```

```yaml
# lib/resources/application-prod.yml: prod プロファイルのときだけ読まれる
shop:
  max-basket-size: 50
```

## 実行する

```bash
dart run build_runner build          # bin/spring_gen/main.spring.dart を書き出す
dart run bin/main.dart               # max-basket-size 20
dart run bin/main.dart --spring.profiles.active=prod   # 50
SHOP_MAXBASKETSIZE=30 dart run bin/main.dart           # 30: 環境変数がファイルより優先される
```

起動時のログ (INFO):

```text
Starting neon-books using Dart 3.13.5 with PID 4242
No active profile set, falling back to 1 default profile: "default"
Started neon-books in 0.07 seconds
NEON Books is open, 20 books per basket
```

`shop.max-basket-size=0` ではアプリケーションは起動しません。キーを示すレポートを出力します。

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

Description:

Binding to target properties under 'shop' failed:

  - shop.max-basket-size: must be greater than or equal to 1 (was "0")

Action:

Update the application's configuration (lib/resources/application.properties, command line or environment).
```

## 仕組み

Dart には実行時のリフレクションがないため、スキャンはビルド時に行われます。`dart run build_runner build` はパッケージ全体 (`lib/` と `main` のディレクトリ。書くべき `@ComponentScan` はありません) を読み、次のものを含む `spring_gen/main.spring.dart` を生成します。

- パッケージの Bean 定義。
- `lib/resources/` のファイル。どのビルドでも動くように埋め込まれます。
- すべての依存関係の自動構成モジュール。
- `springApplication` ゲッターと `runApplication`、`runApplicationAsync` 関数。`reloadApplication` と `reloadApplicationAsync` は `main.spring.debug.dart` にあり、デバッグとプロファイルのビルドだけが使います。

その後 `runApplication(args)` が、Spring Boot の `SpringApplication.run` と同じことを行います。その手順は [SpringApplication](spring-application.md) にあります。

## 内容

起動:

- [SpringApplication](spring-application.md): 起動の手順、コンストラクター、`run` と `runAsync`、バナー、遅延起動。
- [ランナー](runners.md): `ApplicationRunner`、`CommandLineRunner`、`ApplicationArguments`。
- [イベント](events.md): 起動時のイベントと、アプリケーションの可用性。
- [シャットダウンと終了コード](shutdown.md): シャットダウンフック、シャットダウンのタイムアウト、`SpringApplication.exit`。
- [失敗レポート](failure-analysis.md): `APPLICATION FAILED TO START`、`FailureAnalyzer`、条件レポート。
- [ホットリロード](hot-reload.md): Bean が変わったときにコンテキストを再起動する、Flutter と Dart VM のリロード。

外部設定:

- [概要](configuration/index.md): すべてのソースと、どれが優先されるか。
- [設定ファイル](configuration/config-files.md): YAML と `.properties`、ドキュメント、検索ロケーション。
- [プロファイル](configuration/profiles.md): 有効化、グループ、プロファイルファイル、`on-profile` ドキュメント、クラウドプラットフォーム。
- [インポート](configuration/imports.md): `spring.config.import` と、あらゆる種類のロケーション。ファイル、ディレクトリ、設定ツリー、HTTP、パッケージ、アセット。
- [コマンドライン、環境変数、--dart-define](configuration/sources.md): その他のソース、緩い名前、`SPRING_APPLICATION_JSON`、プレースホルダー。
- [@ConfigurationProperties](configuration-properties.md): 型付きの設定、バインド、変換、バリデーション。

自動構成:

- [自動構成とスターター](auto-configuration.md): スターターが Bean を追加する方法、その順序、除外、ビルドから除かれるモジュール、スターターの書き方。
- [条件](conditions.md): すべての `@ConditionalOn...` アノテーション。
- [組み込みの Bean](built-in-beans.md): `ObjectMapper`、バリデーター、メッセージソース、ライフサイクルプロセッサー、可用性の Bean。
- [ログレベル](logging-levels.md): `logging.level.*` と `logging.group.*`、`--debug` と `--trace`。
- [バージョンと互換性](compatibility.md): リリーストレインと `requires` のチェック。

リファレンス:

- [すべてのプロパティ](properties.md): `spring_boot_dart` が読むすべてのキー。
- [Spring との違い](differences.md): Spring Boot と動作が異なる点。

## Spring (Java) との対応

```java
@SpringBootApplication
public class NeonBooks {
  public static void main(String[] args) {
    SpringApplication.run(NeonBooks.class, args);
  }
}
```

重要な違い:

- `@SpringBootApplication()` はクラスではなく `main` 関数に付け、パッケージはビルド時にスキャンされます。アノテーションを変更したりスターターを追加したりしたら、`build_runner` を実行してください。
- `lib/resources/` がクラスパスの役割を果たします。ロケーションは `classpath:` ではなく `resources:` と書きます。
- シャットダウンフックはデフォルトで無効です (`spring.main.register-shutdown-hook=true` で有効になります)。シグナルを待ち受ける Dart プログラムは、自分からは終了しないためです。
- いくつかのプロパティのプレフィックスは名前が変わっており (`spring.jackson.*` は `spring.json.*`)、古い名前は起動を止めます。
- すべての違いは [Spring との違い](differences.md) にあります。

## 関連項目

- [spring_core_dart](../spring-core-dart/index.md)
- [ジェネレーター: @SpringBootApplication](../spring-core-dart-generator/spring-boot-application.md)
- [spring_boot_starter_web](../spring-boot-starter-web/index.md)
- [spring_boot_starter_logging](../spring-boot-starter-logging/index.md)
- [spring_boot_starter_test](../spring-boot-starter-test/index.md)
