spring_core_dart_generator
spring_core_dart_generator は Spring for Dart のコードジェネレーターです。build_runner を実行すると、コードのアノテーション (@Service、@Value、@Bean、@Aspect、@RestController など) を読み、オブジェクトを生成して結び付ける素の Dart コードを書き出します。コードから呼び出すことはありません。開発用の依存関係として追加し、build_runner を実行するだけです。
spring_core_dart、spring_boot_dart、またはいずれかのスターターを使うすべてのアプリケーションに必要です。生成コードがなければアノテーションは何もしません。誰も読まない定数オブジェクトにすぎません。
使う理由
Spring (Java) は、アプリケーションの起動時にアノテーション付きのクラスを見つけます。クラスパスをスキャンし、リフレクションでアノテーションを読み、リフレクションで Bean を生成します。
Dart は、実行される場所のほとんどでこれができません。
- Flutter、AOT 実行ファイル (
dart compile exe)、Web にはdart:mirrorsがないため、プログラムは実行時に自分のクラスを列挙することも、そのアノテーションを読むこともできません。 dart:mirrorsがある場所 (JIT モードの Dart VM) でも、それを使うプログラムはツリーシェイキングで未使用のコードを取り除けません。どのクラスも名前で検索される可能性があるからです。
そこで、この作業をビルド時に移します。build_runner はジェネレーターに、アナライザーが見るコードの全体像を渡します。すべてのクラス、コンストラクター、パラメーターの型、アノテーションの値です。ジェネレーターは Spring が起動時に答える問い (どのクラスが Bean か、各コンストラクターが何を必要とするか、どのメソッドがイベントリスナーか、アスペクトがどの Bean にアドバイスできるか) に答え、その答えを Dart コードとして書き出します。
- リフレクションによるインスタンス化の代わりに、Bean ごとのコンストラクター呼び出し。
- リフレクションによるフィールドアクセスの代わりに、注入されるフィールドやセッターごとのクロージャー。
- 実行時のプロキシの代わりに、アドバイスされる Bean ごとの生成されたプロキシクラス。
- アノテーション、プロパティ名、
lib/resources/のファイルの定数。
このコードはすべてのプラットフォームで動き、ミニファイに耐え、何も使わないものをコンパイラーが取り除けるようにします。また、アプリケーションが実行される前に、多くの間違い (置き場所の誤ったアノテーション、不正なポイントカット、private な Bean の型) をビルドが報告できます。
インストール
# pubspec.yaml
dependencies:
spring_boot_dart: ^0.9.0 # または spring_boot_starter_web などのスターター
dev_dependencies:
build_runner: ^2.17.0
spring_core_dart_generator: ^0.9.0 # 必須: Bean 定義を書き出す
他には何も要りません。ジェネレーターのビルダーは、それに依存するすべてのパッケージに自動で適用されます (build.yaml の auto_apply: dependents)。そのため、オプションを変えたい場合を除いて、自分のパッケージに build.yaml を書く必要はありません。
ジェネレーターは spring_boot_dart やスターターに依存しません。それらのアノテーションを名前とライブラリの URL で認識するので、spring_core_dart だけでも使えます。
最初の実行
dart run build_runner build # 一度生成する
dart run build_runner watch # 保存のたびに再生成する
アノテーション、Bean、lib/resources/ のファイルを追加、削除、変更したら build を実行します。開発中は、watch が入力に合わせて生成ファイルを最新に保ちます。watch では、構文エラーのあるファイルがあっても生成コードは削除されません。ソースが再び解析できるようになるまで、最後の正常な版が残ります (生成の仕組み を参照)。
build_runner が他のジェネレーターとの出力の衝突を報告した場合は、--delete-conflicting-outputs を追加します。
現れるファイル
生成ファイルは、それが属するソースルートの最上位にある spring_gen/ フォルダーに置かれ、残りのパスはそのまま写されます。
my_app/
bin/
main.dart # 自分のファイル: main に @SpringBootApplication()
spring_gen/
main.spring.dart # 生成: アプリケーション全体
lib/
src/
beans.dart # 自分のファイル: @ComponentScan() 変数
spring_gen/
src/
beans.spring.dart # 生成: lib/src/ の Bean
spring_metadata.json # 生成: エディター向けのプロパティと Bean
test/
shop_test.dart # 自分のファイル: @SpringBootTest クラス
spring_gen/
shop.test.spring.dart # 生成: runSpringTests()
生成ファイルができるのは、自分のファイルのうちごく一部だけです。
| 自分のファイル | 生成ファイル | ページ |
|---|---|---|
main に @SpringBootApplication() を持つライブラリ |
アプリケーション全体を含む <root>/spring_gen/<path>.spring.dart |
@SpringBootApplication |
@ComponentScan() 変数を持つライブラリ |
BeanModule を一つ含む <root>/spring_gen/<path>.spring.dart |
@ComponentScan モジュール |
@SpringBootTest または @DataTest クラスを持つ test/<name>_test.dart |
test/spring_gen/<name>.test.spring.dart |
テスト |
| Spring のコードを持つパッケージ | lib/spring_gen/spring_metadata.json |
エディター向けのメタデータ |
それ以外の Dart ファイルは、簡単なテキストチェックの後にスキップされます。Flutter アプリにはさらにいくつかのファイル (型付きのテーマキーとメッセージキー、web/index.html のページローダーなど) ができます。ビルダー を参照してください。
生成ファイルは他のコードと一緒にコミットします。生成ファイルはプログラムの一部です。main.dart は main.spring.dart をインポートし、公開されたパッケージは生成されたモジュールと spring_metadata.json を同梱します。
完全な例
コマンドラインアプリケーションならファイル一つで十分です。
// bin/main.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'spring_gen/main.spring.dart'; // ジェネレーターが書き出す
@Component()
class Greeter {
// 設定値。コロンの後がデフォルト。
Greeter(@Value(r'${greeting.punctuation:!}') this.punctuation);
final String punctuation;
String greet(String name) => 'Hello, $name$punctuation';
}
@Component()
class Hello implements CommandLineRunner {
Hello(this.greeter);
final Greeter greeter;
@override
void run(List<String> args) => print(greeter.greet('Ada'));
}
@SpringBootApplication()
void main(List<String> args) => runApplication(args);
dart run build_runner build は bin/spring_gen/main.spring.dart を書き出します。簡略化すると次のとおりです (実際のファイルは各ライブラリを _i1. のようなプレフィックス付きでインポートし、Bean ごとに aopProxy: 引数を書き、より多くの --dart-define キーを列挙します)。
// GENERATED CODE - DO NOT MODIFY BY HAND
// Generated by spring_core_dart_generator from @ComponentScan.
/// Beans found by `@ComponentScan` in `lib/ and bin/`.
BeanModule get $application => BeanModule(r'application', [
BeanDefinition<Greeter>(
name: r'greeter',
source: r'asset:my_app/bin/main.dart#Greeter',
dependencies: const [Dependency.value(r'${greeting.punctuation:!}')],
create: (r) => Greeter(r.value<String>(r'${greeting.punctuation:!}')),
annotations: const [Component()],
),
BeanDefinition<Hello>(
name: r'hello',
source: r'asset:my_app/bin/main.dart#Hello',
types: const [Hello, CommandLineRunner],
dependencies: const [Dependency(Greeter, name: r'greeter')],
create: (r) => Hello(r.dependency<Greeter>(name: r'greeter')),
annotations: const [Component()],
),
]);
/// The `@SpringBootApplication` of the current code (a getter, so it is
/// up to date after a hot reload).
SpringApplication get springApplication => SpringApplication(
[$application],
autoConfigurations: [springBootAutoConfiguration],
dartDefines: {
if (const bool.hasEnvironment('GREETING_PUNCTUATION'))
'GREETING_PUNCTUATION': const String.fromEnvironment('GREETING_PUNCTUATION'),
if (const bool.hasEnvironment('greeting.punctuation'))
'greeting.punctuation': const String.fromEnvironment('greeting.punctuation'),
// ... と、すべてのアプリケーションが読みうるキー (SPRING_PROFILES_ACTIVE など)
},
fingerprint: !const bool.fromEnvironment('dart.vm.product')
? _$fingerprint
: null,
);
ConfigurableApplicationContext runApplication(List<String> args) =>
springApplication.run(args, hotReload: () => springApplication);
// runApplicationAsync ...
// main.spring.debug.dart: a part, compiled in debug and profile builds only
const _$fingerprint = '3ada566f';
// reloadApplication, reloadApplicationAsync ...
注目すべき点:
- 各 Bean はコンストラクター呼び出しです。
createはリゾルバーrを受け取り、引数ごとにそれを問い合わせます。型とパラメーター名による Bean、または解決済みのプロパティ値です。リフレクションは関わりません。 dependenciesはcreateが問い合わせるものを列挙します。 コンテナはこれを読み、何かを生成する前に、足りない Bean と循環を見つけます。typesは Bean を検索できる型を列挙します。 クラス自身だけの場合 (実行時のデフォルト) は省略されます。HelloはCommandLineRunnerも実装しているので列挙されています。- アプリケーションは完全です。
springApplicationは Bean、依存関係にあるすべてのスターターの自動構成、プログラムが読みうる--dart-defineキーを保持します。runApplicationがそれを起動します。
実行します。
dart run bin/main.dart # Hello, Ada!
dart run bin/main.dart '--greeting.punctuation=?' # Hello, Ada?
@SpringBootApplication のないライブラリは、代わりに @ComponentScan() 変数を使い、モジュールを自分でコンテキストに渡します。
// 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;
// 別の場所で
final context = ApplicationContext.run([appBeans]);
次に読むページ
はじめに:
生成されるコード:
- @ComponentScan モジュール: ディレクトリごとに一つのモジュール、入れ子のスキャン、フィルター。
- アプリケーション: @SpringBootApplication: パッケージ全体、
runApplicationとホットリロード。 - Bean 定義: 各アノテーションが
BeanDefinitionのどの部分になるか。 - 自動構成: アプリケーションの中のスターターのモジュール。
- 埋め込みリソース: すべてのプラットフォームでの
lib/resources/のファイル。 - --dart-define キー: Flutter、Web、AOT 向けのビルド時の値。
- @Log:
logゲッター。 - テスト:
@SpringBootTestと@DataTest。 - データ: エンティティ、リポジトリ、クエリ。
その他:
- 最適化: 実行されるコードだけが生成されます。
- Flutter: 型付きキー、Web 開発サーバー、ページローダー、検索エンジン、ディープリンク。
- ビルド時のチェック と エラーと生成ファイル。
- オプション、ビルドが読むプロパティ、エディター向けのメタデータ、Spring との違い。
Spring (Java) との対応
// 従来の Spring はコンテキストの起動時に Bean を見つける:
// ClassPathBeanDefinitionScanner がクラスファイルを読み、リフレクションが
// インスタンスを生成する。
var context = new AnnotationConfigApplicationContext();
context.scan("com.example.app");
context.refresh();
最も近い Spring の機能は Spring 6 AOT (BeanFactoryInitializationAotProcessor) で、GraalVM ネイティブイメージ向けに、ビルド時に Bean 定義の Java ソースを書き出せます。Spring for Dart ではこれは選択肢ではなく、すべてのプラットフォームで唯一の方法です。
関連項目
- spring_core_dart: ジェネレーターが読むアノテーション。
- BeanModule: 生成されたモジュールが実行時に何であるか。
- @ComponentScan: アノテーションそのもの。