
# 組み込みの Bean

`spring_boot_dart` もスターターです。その自動構成モジュール `springBootAutoConfiguration` は、すべてのアプリケーションに次の自動構成を追加します。それぞれ、アプリケーションが独自の Bean を宣言すると身を引き、名前で除外することもできます。

| 自動構成 | Bean | アプリケーションが次のものを持つと身を引く |
|---|---|---|
| `JacksonAutoConfiguration` | `jacksonJsonMapper` (`ObjectMapper`) | `ObjectMapper` の Bean |
| `ValidationAutoConfiguration` | `defaultValidator` (`BeanValidator`) と `methodValidationPostProcessor` | `BeanValidator` の Bean。`MethodValidationPostProcessor` の Bean |
| `MessageSourceAutoConfiguration` | `messageSource` | このコンテキストにある `messageSource` という名前の Bean、またはバンドルファイルがないこと |
| `LifecycleAutoConfiguration` | シャットダウンのタイムアウトを持つ `lifecycleProcessor` | このコンテキストにある `lifecycleProcessor` という名前の Bean |
| `ApplicationAvailabilityAutoConfiguration` | `applicationAvailability` | `ApplicationAvailability` の Bean |
| `JsonSchemaAutoConfiguration` | `jsonSchemaRegistry` | `JsonSchemaRegistry` の Bean |
| `ObservationAutoConfiguration` | `observationRegistry`。すべての `ObservationHandler` の Bean を持つ | `ObservationRegistry` の Bean |
| `IsolateAutoConfiguration` | `isolateInfo`、`isolateLoadSampler`、`isolateTaskExecutor`、`isolateLoads`、`isolateReports`、`primaryIsolate` | 同じ型の Bean。それぞれ個別に |

別のモジュールである `springBootObservedAnnotationsAutoConfiguration` は、`@Observed` を有効にする `observedAdvisor` を追加します。これは `spring.observations.annotations.enabled: true` のときだけで、そうでなければモジュールはビルドに含まれず、どの Bean も `@Observed` のためのプロキシを得ません。[観測と起動](../spring-core-dart/observations/index.md) を参照してください。

## 使う理由

ほぼすべてのアプリケーションに、JSON、バリデーション、翻訳されたメッセージ、きれいなシャットダウンが必要です。Spring Boot はそれらをプロパティから構成します。`spring_boot_dart` も、意味のある範囲で同じ名前を使って同様に構成します。独自の Bean を宣言するとデフォルトは完全に置き換えられるため、隠れたものは何もありません。

## 例

```yaml
# lib/resources/application.yml
spring:
  json:
    property-naming-strategy: SNAKE_CASE
    default-property-inclusion: non_null
    serialization:
      indent-output: true
  messages:
    basename: messages,i18n/errors
    fallback-to-system-locale: false
  lifecycle:
    timeout-per-shutdown-phase: 20s
```

```dart
// マッパー、バリデーター、メッセージソースはすぐに注入できる。
@Service()
class Catalog {
  Catalog(this.mapper, this.validator, this.messages);

  final ObjectMapper mapper;
  final Validator validator;
  final MessageSource messages;

  String export(List<Book> books) => mapper.writeValueAsString(books);
  List<Book> import(String json) => mapper.readList<Book>(json);
}
```

```properties
# 一つを無効にする
spring.autoconfigure.exclude=JacksonAutoConfiguration
```

## JSON: ObjectMapper

`jacksonJsonMapper` Bean (Spring Boot 4 の名前) は JSON を読み書きします。Web スターターは、リクエストとレスポンスのボディに同じ Bean を使います。アプリケーションのすべての `@Introspected` クラスを知っており、すべての `JsonSerializer`、`JsonDeserializer`、`JsonModule` の Bean (Spring Boot の `@JsonComponent`) を追加します。

| キー | デフォルト | 意味 |
|---|---|---|
| `spring.json.property-naming-strategy` | `LOWER_CAMEL_CASE` | フィールド名を JSON の名前にする方法: `SNAKE_CASE`、`UPPER_SNAKE_CASE`、`UPPER_CAMEL_CASE`、`LOWER_CAMEL_CASE`、`LOWER_CASE`、`KEBAB_CASE`、`LOWER_DOT_CASE` |
| `spring.json.default-property-inclusion` | `always` | 書き出すプロパティ: `always`、`non_null`、`non_absent`、`non_empty`、`non_default` |
| `spring.json.time-zone` | なし: 各日時はそれ自身のタイムゾーン | `UTC`、`Z`、または固定オフセット (`+02:00`)。名前付きのタイムゾーン (`Europe/Berlin`) は起動を止める: Dart にはタイムゾーンデータベースがない |
| `spring.json.serialization.indent-output` | `false` | 整形した JSON |
| `spring.json.serialization.write-dates-as-timestamps` | `false` | `DateTime` を小数部付きのエポック秒として (Jackson 3) |
| `spring.json.serialization.write-durations-as-timestamps` | `false` | `Duration` を秒として |
| `spring.json.serialization.write-date-timestamps-as-nanoseconds` | `true` | `false`: タイムスタンプをミリ秒で |
| `spring.json.deserialization.read-date-timestamps-as-nanoseconds` | `true` | 整数のタイムスタンプは秒。`false`: ミリ秒 |
| `spring.json.deserialization.fail-on-unknown-properties` | `false` | クラスにない JSON のプロパティがあると読み込みが失敗する |
| `spring.json.deserialization.accept-float-as-int` | `true` | `int` への `1.5` は切り捨てられる。`false` は拒否する |
| `spring.json.deserialization.fail-on-null-for-primitives` | `true` | nullable でない `int`、`double`、`num`、`bool` への `null` (またはコンストラクターの値の欠落) で読み込みが失敗する。`false` は `0` または `false` を読む |
| `spring.json.mapper.sort-properties-alphabetically` | `true` | プロパティを JSON の名前で並べ、コンストラクターのパラメーターを先にする (Jackson 3 の順序)。`false`: 宣言順 |
| `spring.json.mapper.default-view-inclusion` | `false` | `@JsonView` のないプロパティをビュー付きで書き出す |
| `spring.json.datatype.datetime.write-dates-as-timestamps` | `serialization.` の値 | Spring Boot 4 の名前。`serialization.` のキーより優先される |
| `spring.json.datatype.datetime.write-durations-as-timestamps` | `serialization.` の値 | `serialization.` のキーより優先される |
| `spring.json.datatype.datetime.write-date-timestamps-as-nanoseconds` | `serialization.` の値 | `serialization.` のキーより優先される |
| `spring.json.datatype.datetime.read-date-timestamps-as-nanoseconds` | `deserialization.` の値 | `deserialization.` のキーより優先される |

真偽値は厳密にバインドされ、真偽値でない値は起動を止めます。それ以外の `spring.json.*` のキー (`date-format`、`locale`、Jackson の機能フラグ) は、対応するキーを示す警告としてログに出され、無視されます。`spring.jackson.*` は起動を止め、新しいキーを示します。

プロパティを失わずに一つだけ変えるには、`JsonMapperBuilderCustomizer` の Bean (Spring Boot 4 のもの) を宣言します。カスタマイザーはプロパティが適用された後に `@Order` の順で実行されるため、それらが優先されます。

```dart
// プロパティにかかわらず、整形した JSON。
@Bean()
JsonMapperBuilderCustomizer indented() => JsonMapperBuilderCustomizer.of(
      (builder) => builder.enable(SerializationFeature.indentOutput),
    );
```

`objectMapperFromProperties(environment)` は、Bean を使わないツール、テスト、2 つ目のマッパーのために、同じマッパーを手で組み立てます。[JSON](../spring-core-dart/json/index.md) を参照してください。

アプリケーションの JSON Schema (`spring.json.schemas`、`@JsonSchemaSource`) は独立した Bean で、マッパーはそれらに照らして JSON を検査します。[JSON Schema の Bean](json-schema.md) を参照してください。

## バリデーション

- `defaultValidator` は、`@NotBlank()` のような制約アノテーションをチェックする `BeanValidator` です。オブジェクトを手で検証するには `Validator` を注入します。独自の `BeanValidator` Bean はこれを置き換えますが、単純な `Validator` インターフェースだけを実装する Bean は置き換えません。
- `methodValidationPostProcessor` は、`@Validated()` を付けた Bean のメソッドのパラメーターと戻り値をチェックします。`BeanValidator` の Bean が一つならそれを使い、ないか複数あれば新しいものを使います。`@ConfigurationProperties` のクラスは対象外です。そこでの `@Validated()` は、バインド後のバリデーションを意味します。

デフォルトのバリデーターはメッセージソースを持たないため、制約メッセージの `{key}` は検索されず、書いたとおりに残ります。[バリデーション](../spring-core-dart/validation/index.md) を参照してください。

## メッセージ

`messageSource` は、`lib/resources/messages.properties` と `messages_<locale>.properties` から翻訳されたテキストを読みます。設定されたベース名のバンドルファイルが存在し、かつコンテキスト (親は数えない) に `messageSource` という名前の Bean がない場合にだけ登録されます。

| キー | 型 | デフォルト | 意味 |
|---|---|---|---|
| `spring.messages.basename` | リスト | `messages` | ベース名。`i18n/errors` (または `i18n.errors`) は `lib/resources/i18n/errors_{locale}.properties` を読む |
| `spring.messages.encoding` | 文字セット | UTF-8 | ファイルのエンコーディング。不明なものは起動を止める |
| `spring.messages.cache-duration` | `Duration`。単なる数値は秒 | 永久に保持 | 読み込んだファイルを再び読むまで保持する時間 |
| `spring.messages.fallback-to-system-locale` | bool | `true` | ロケールなしのファイルの前に、システムのロケールを試す |
| `spring.messages.use-code-as-default-message` | bool | `false` | 見つからないキーは、失敗する代わりにキー自身を返す |
| `spring.messages.always-use-message-format` | bool | `false` | 引数のないメッセージも書式化するため、`''` は `'` になる |
| `spring.messages.default-locale` | ロケール | なし | システムのロケールの前に試すロケール (Spring Boot にはない。アプリには意味のあるシステムロケールがないことが多い) |
| `spring.messages.common-messages` | ロケーションのリスト | なし | すべてのロケールで共有するテキスト。後のファイルが優先される |

[メッセージ](../spring-core-dart/messages/index.md) を参照してください。

## ライフサイクルプロセッサー

コンテキストが閉じるとき、`lifecycleProcessor` はライフサイクルの Bean をフェーズごとに停止し、各フェーズを最大 `spring.lifecycle.timeout-per-shutdown-phase` (Spring Boot と同じくデフォルトは 30 秒) だけ待ちます。たとえば Web サーバーのグレースフルシャットダウンを待ちます。この Bean がない場合、プロパティにかかわらず、コンテキスト自身のプロセッサーは 10 秒 (Spring Framework のデフォルト) 待ちます。[シャットダウン](shutdown.md) を参照してください。

## 可用性

`applicationAvailability` は、最後の `LivenessState` と `ReadinessState` を保持します。[イベント](events.md#可用性) を参照してください。

## isolate

`IsolateAutoConfiguration` は次の Bean を宣言します。最初の六つは、それぞれ、アプリケーションがその型の Bean を宣言すると除外されます。

| Bean | 型 | 何か |
|---|---|---|
| `isolateInfo` | `IsolateInfo` | コンテキストが動いている isolate: その名前、プールでの番号、アプリケーションの最初の isolate かどうか |
| `isolateLoadSampler` | `IsolateLoadSampler` | その isolate がどれだけ働いているか。誰かが読んでいる間だけ計測し、コンテキストとともに止まる |
| `isolateTaskExecutor` | `IsolateTaskExecutor` | ブロックしてしまう処理のための isolate のプール。`spring.task.execution.isolates.*` で設定する。最初のタスクまで isolate を起動せず、コンテキストとともにシャットダウンされる |
| `isolateLoads` | `IsolateLoads` | 知られているすべての isolate の負荷。各 `IsolateLoadSource` の Bean から得る: 上の二つ、Web サーバーのもの、独自のもの |
| `isolateReports` | `IsolateReports` | プールの各 isolate が最初の isolate に伝えるもの。各 `IsolateReporter` の Bean から得る |
| `primaryIsolate` | `PrimaryIsolate` | アプリケーションの最初の isolate に問い合わせる。そこで各 `PrimaryIsolateHandler` の Bean が応答する。どの isolate でも同じ呼び出し |
| `isolateLoadsHandler` | `IsolateLoadsHandler` | そうしたハンドラーの一つ (`isolates.loads`): すべての isolate の負荷を応答するので、どの isolate に届いたリクエストでもそのすべてを表示できる |

どれも、使われるまでは何のコストもかかりません。負荷を一度も読まず、タスクを一度も投入しないアプリケーションでは、タイマーは動かず、isolate も起動されません。

```dart
@Service()
class Thumbnails {
  Thumbnails(this.isolates, this.isolate);
  final IsolateTaskExecutor isolates;
  final IsolateInfo isolate;

  // リサイズは、リクエストに応答したり描画したりする isolate をブロックしてしまう。
  Future<Uint8List> resize(Uint8List image) =>
      isolates.submitWith(_resize, image);

  static Uint8List _resize(Uint8List image) => /* ... */ image;
}
```

Web サーバーのプールの isolate では、タスクエグゼキューターの isolate はその isolate の名前を持ちます (`isolate-2-task-1`)。そのため、アプリケーションのすべてのタスク用の isolate が独自の名前を持ちます。

ブラウザーでは、`isolateTaskExecutor` はタスクを呼び出し元の isolate で実行します。そこでは isolate を起動できないためです。それを使うコードは同じです。

[isolate](../spring-core-dart/isolates/index.md)、[タスクエグゼキューター](../spring-core-dart/isolates/task-executor.md)、[isolate の負荷](../spring-core-dart/isolates/load.md)、[最初の isolate に問い合わせる](../spring-core-dart/isolates/primary-isolate.md) を参照してください。`@ConditionalOnPrimaryIsolate` は [条件](conditions.md#conditionalonprimaryisolate) にあります。

## Spring (Java) との対応

Spring Boot の `TaskExecutionAutoConfiguration` がタスクエグゼキューターに対応します。その他の isolate の Bean に対応するものはありません。自動構成の名前もプロパティも同じですが、`spring.jackson.*` は `spring.json.*` で、読まれるのは上記のキーだけです。`JsonMapperBuilderCustomizer` が受け取るのは、Jackson の完全なビルダーではなく、中核の `JsonMapperBuilder` (命名、包含、タイムゾーン、機能、シリアライザー、モジュール) です。

## 関連項目

- [自動構成とスターター](auto-configuration.md)
- [isolate](../spring-core-dart/isolates/index.md)
- [すべてのプロパティ](properties.md)
- [JSON](../spring-core-dart/json/index.md)
- [JSON Schema の Bean](json-schema.md)
- [バリデーション](../spring-core-dart/validation/index.md)
- [メッセージ](../spring-core-dart/messages/index.md)
