spring_boot_dart
spring_boot_dart は、Spring for Dart のうちアプリケーションを起動する部分です。Spring Boot の SpringApplication、その外部設定、@ConfigurationProperties のバインド、そして自動構成を Dart に移植したものです。
spring_core_dart だけでも Bean のコンテナは手に入りますが、起動処理は自分で書くことになります。設定ファイルを読み、コンテキストを生成し、ログレベルを設定し、起動時の処理を実行します。spring_boot_dart は、main に付けた一つのアノテーションでそのすべてを行います。
使う理由
どのアプリケーションにも同じ起動コードが必要で、しかも間違えやすいものです。
- ファイル、環境変数、コマンドライン、
--dart-defineからの設定。devやprodのようなプロファイル。どのソースが優先されるかについての明確なルール。 - 自分のパッケージの Bean と、依存するライブラリ (「スターター」) の Bean。自分の Bean は常にスターターのものより優先されます。
- 設定のグループを型付きのクラスにバインドし、Bean が使う前に変換と検証を行うこと。
- 起動時のタスクを順に実行し、各段階でイベントを発行し、きれいにシャットダウンすること。
- 起動できないときに、スタックトレースではなく読みやすいレポートを出すこと。
spring_boot_dart は、これらすべてを Spring Boot の名前とルールで提供します。そのため、Spring プロジェクトの設定や習慣をそのまま持ち込めます。サーバーでも、コマンドラインツールでも、Flutter アプリでも、Dart VM、AOT ビルド、Web のいずれでも同じように動きます。
セットアップ
# 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、...) がこれに依存し、エクスポートしているためです。
例
型付きの設定、起動時のタスク、プロファイルを持つ完全なアプリケーションです。
// 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);
# lib/resources/application.yml
spring:
application:
name: neon-books
shop:
max-basket-size: 20
logging:
level:
root: info
# lib/resources/application-prod.yml: prod プロファイルのときだけ読まれる
shop:
max-basket-size: 50
実行する
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):
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 ではアプリケーションは起動しません。キーを示すレポートを出力します。
***************************
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 にあります。
内容
起動:
- SpringApplication: 起動の手順、コンストラクター、
runとrunAsync、バナー、遅延起動。 - ランナー:
ApplicationRunner、CommandLineRunner、ApplicationArguments。 - イベント: 起動時のイベントと、アプリケーションの可用性。
- シャットダウンと終了コード: シャットダウンフック、シャットダウンのタイムアウト、
SpringApplication.exit。 - 失敗レポート:
APPLICATION FAILED TO START、FailureAnalyzer、条件レポート。 - ホットリロード: Bean が変わったときにコンテキストを再起動する、Flutter と Dart VM のリロード。
外部設定:
- 概要: すべてのソースと、どれが優先されるか。
- 設定ファイル: YAML と
.properties、ドキュメント、検索ロケーション。 - プロファイル: 有効化、グループ、プロファイルファイル、
on-profileドキュメント、クラウドプラットフォーム。 - インポート:
spring.config.importと、あらゆる種類のロケーション。ファイル、ディレクトリ、設定ツリー、HTTP、パッケージ、アセット。 - コマンドライン、環境変数、--dart-define: その他のソース、緩い名前、
SPRING_APPLICATION_JSON、プレースホルダー。 - @ConfigurationProperties: 型付きの設定、バインド、変換、バリデーション。
自動構成:
- 自動構成とスターター: スターターが Bean を追加する方法、その順序、除外、ビルドから除かれるモジュール、スターターの書き方。
- 条件: すべての
@ConditionalOn...アノテーション。 - 組み込みの Bean:
ObjectMapper、バリデーター、メッセージソース、ライフサイクルプロセッサー、可用性の Bean。 - ログレベル:
logging.level.*とlogging.group.*、--debugと--trace。 - バージョンと互換性: リリーストレインと
requiresのチェック。
リファレンス:
- すべてのプロパティ:
spring_boot_dartが読むすべてのキー。 - Spring との違い: Spring Boot と動作が異なる点。
Spring (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 との違い にあります。