
# すべてのスターターのための一つのコンテキスト

Spring for Dart で作るアプリケーションには、**アプリケーションコンテキスト** が一つあります。それは自分の Bean と依存するすべてのスターターの Bean を保持し、一つの `Environment` がすべてのプロパティを保持します。そのため、スターターは自分のコードなしに協調して動きます。Web スターターはコアの `ObjectMapper` で JSON を書き、セキュリティスターターは Web スターターのコントローラーの前に自身のフィルターを置き、キャッシュスターターのアドバイスは自分のサービスを包みます。そして、ある型の自分の Bean はスターターのものを置き換えます。

## スターターの見つけ方

スターターは、決まった名前のファイル `lib/spring_auto_configuration.dart` で Bean を提供します。その中で、トップレベルの `BeanModule` 変数が `@AutoConfigurationModule()` を持ちます。これは Web スターターのものです。

```dart
// spring_boot_starter_web/lib/spring_auto_configuration.dart
import 'package:spring_boot_dart/spring_boot_dart.dart';
import 'package:spring_boot_starter_web/src/config/config.dart';
import 'package:spring_boot_starter_web/src/web_auto_configuration.dart';

export 'package:spring_boot_starter_logging/spring_auto_configuration.dart';

@AutoConfigurationModule()
final BeanModule springBootStarterWebAutoConfiguration = BeanModule(
  'springBootStarterWebAutoConfiguration',
  [...webMvcAutoConfiguration], // サーバー、ルーター、フィルターなど
  imports: [webConfigBeans],    // server.* と spring.mvc.* のプロパティ
);
```

`@SpringBootApplication()` を持つアプリケーションに対して `dart run build_runner build` を実行すると、ジェネレーターは次のことを行います。

1. `pubspec.yaml` のアプリケーションの依存関係を、直接のものも推移的なものもたどります。
2. それを持つ各パッケージの `lib/spring_auto_configuration.dart` を読みます。
3. `@AutoConfigurationModule` を付けたすべての変数を取り、それが `requires` するバージョンをチェックし、`build` 条件があればそれを判定します。
4. それらを生成された `springApplication` に書き込みます。

```dart
// bin/spring_gen/main.spring.dart (生成、簡略化)
SpringApplication get springApplication => SpringApplication(
  [$application],                           // 自分の Bean
  autoConfigurations: [
    springBootAutoConfiguration,            // spring_boot_dart
    springBootStarterLoggingAutoConfiguration,
    springBootStarterWebAutoConfiguration,
  ],
);
```

これは、Spring Boot の `META-INF/spring/...AutoConfiguration.imports` ファイルの Dart 版です。Spring Boot はアプリケーションの起動時にクラスパスからそれらを読みますが、ここではジェネレーターがビルド時にそれらを読みます。そのため、スターターを `pubspec.yaml` に追加したら、`build_runner` を再び実行してください。詳しくは: [自動構成](../components/spring-core-dart-generator/auto-configurations.md)。

## 登録の順序

起動のたびに、`SpringApplication` は次の順で登録します。

1. **まず自分の Bean**。
2. **次に自動構成モジュール**。Spring Boot の `AutoConfigurationSorter` と同じくソートされます。`order` (デフォルトは `0`)、次に名前の順で、その後 `before` と `after` で移動されます。

順序は条件にとって重要です。「存在しない場合だけ」と示されたスターターの Bean は、自分の Bean が登録された後に判定されるので、自分のものを見て身を引きます。スターター間では、`after` がどのスターターの Bean を先に登録すべきかを示します。たとえばアクチュエータースターターのモジュールは `after: ['springBootStarterWebAutoConfiguration']` と宣言されています。`before` と `after` の間に循環があると起動が止まります。

## 共有される一つのコンテキスト

自分のものもスターターのものも、すべての Bean は同じコンテキストにあり、どこにでも注入できます。スターターからの実際の例です。

| スターター | 使うもの | 方法 |
|---|---|---|
| `spring_boot_starter_web` | `spring_boot_dart` の `ObjectMapper` | リクエストとレスポンスのボディは、アプリケーションの一つの `ObjectMapper` Bean で読み書きされる。 |
| `spring_boot_starter_feign` | 同じ `ObjectMapper` | Feign クライアントもそれで JSON をエンコード・デコードするので、クライアントとコントローラーは形式について一致する。 |
| `spring_boot_starter_security` | Web スターターのフィルター | そのフィルターチェーンは `WebFilter` Bean (順序は `-100`、`spring.security.filter.order` から) で、Web スターターはコントローラーより前にすべての `WebFilter` Bean を実行する。 |
| `spring_boot_starter_oauth2_client` | Feign のインターセプター | `spring.feign.oauth2.enabled=true` では、`RequestInterceptor` Bean である `OAuth2AccessTokenInterceptor` を登録する。Feign は `RequestInterceptor` Bean をその呼び出しに適用するので、各呼び出しがトークンを持つ。 |
| `spring_boot_starter_cache`、`spring_boot_starter_data` | 自分の Bean | `cacheAdvisor` と `transactionAdvisor` は AOP のアドバイザー Bean。ジェネレーターが書き出すプロキシを通して、自分の Bean のメソッドに `@Cacheable` と `@Transactional` を適用する。 |
| `spring_boot_starter_actuator` | 自分の Bean、他のスターターの Bean | すべての `HealthIndicator` Bean が `/actuator/health` の一部になる。自分のものも、データスターターの `db` インジケーターも。 |
| `spring_boot_starter_flutter` | ロギングスターターの `LogBuffer` | デバッグパネルのログのセクションは、`LogBuffer` Bean に保持された行を表示する。 |
| `spring_boot_starter_logging` | すべて | すべてのパッケージは `SpringLog` を通してログを出す。ロギングスターターが、行の行き先とレベルを決める。 |

自分の Bean も同じように参加します。自分の `WebFilter` は、`@Order` で並べられて、セキュリティフィルターと同じチェーンで実行されます。

```dart
// セキュリティフィルター (-100) の後に実行される: それが通したリクエストだけ。
@Component()
@Order(0)
class AuditFilter implements WebFilter {
  AuditFilter(this.audit);

  final AuditLog audit; // 自分の Bean

  @override
  Future<void> doFilter(
    ServerHttpRequest request,
    ServerHttpResponse response,
    WebFilterChain chain,
  ) {
    audit.record('${request.method.value} ${request.path}');
    return chain.doFilter(request, response);
  }
}
```

そして自分の `HealthIndicator` は、登録なしにアクチュエーターのレポートに現れます。

```dart
@Component()
class OrdersHealthIndicator extends HealthIndicator {
  OrdersHealthIndicator(this.orders);

  final Orders orders;

  @override
  Future<Health> health() async => await orders.reachable()
      ? Health.up().withDetail('pending', await orders.pending()).build()
      : Health.down().build();
}
```

## 条件

スターターの Bean 定義は、起動時にそもそも登録されるかどうかを決める条件を持ちます。

| 条件 | 登録される場合 |
|---|---|
| `@ConditionalOnMissingBean` | その型 (または名前) の Bean がまだ存在しない。こうして自分の Bean がスターターのものを置き換える。 |
| `@ConditionalOnBean` | その型 (または名前) の Bean が存在する |
| `@ConditionalOnSingleCandidate` | その型の Bean がちょうど一つ存在する、または一つがプライマリーである |
| `@ConditionalOnProperty` | プロパティが値を持つ (`havingValue:`、`matchIfMissing:`) |
| `@ConditionalOnBooleanProperty` | プロパティが `true` |
| `@ConditionalOnExpression` | SpEL 式が真 |
| `@ConditionalOnResource` | リソースが存在する |
| `@ConditionalOnCloudPlatform` | アプリケーションが Kubernetes のようなプラットフォームで動いている |
| `@Profile([...])` | アクティブなプロファイルが一致する |
| `@Conditional(...)` | 独自の `Condition` がそう言う |

スターターから:

- Web スターターの `webServerFactory` は `ConditionalOnMissingBean(WebServerFactory)` を、その `multipartResolver` は `ConditionalOnMissingBean(MultipartResolver)` を持ちます。
- `spring_boot_dart` の `ObjectMapper` は `ConditionalOnMissingBean(ObjectMapper)` を、キャッシュスターターの `cacheManager` は `ConditionalOnMissingBean(CacheManager)` を持ちます。
- ロギングスターターは `logging.enabled=false` でない限り有効で、スケジューリングスターターは `spring.task.scheduling.enabled=false` でない限り有効です (`ConditionalOnProperty(..., matchIfMissing: true)`)。
- セキュリティスターターの `defaultSecurityFilterChain` (すべてのリクエストにログインが必要) は、アプリケーションが `SecurityFilterChain` を宣言していない場合にだけ登録されます。

`@ConditionalOnClass` はありません。Java ではライブラリがクラスパスにあるかを問いますが、Dart では依存関係のグラフがビルド時にわかるので、代わりにジェネレーターが判定します。スターターのモジュールがアプリケーションに含まれるのはスターターが依存関係である場合だけで、モジュールはプロパティによってビルドから外せます ([ビルドから外されるモジュール](../components/spring-core-dart-generator/optimizations/build-conditions.md) を参照)。データスターターもデータベースについて同じように動きます。ジェネレーターは、アプリケーションが依存する各ドライバーパッケージ (`sqlite3`、`postgres`) について `JdbcDriver` Bean を書き出し、それ以外では何も書き出しません。

Bean がなぜあるのか、なぜないのかを見るには、`--debug` (または `debug=true`) で起動します。条件評価レポートが、一致した条件と一致しなかった条件を列挙します。詳しくは: [@Conditional](../components/spring-core-dart/beans/conditional.md)。

## スターターの Bean を置き換える

同じ型の Bean を宣言します。スターターの `@ConditionalOnMissingBean` が自分のものを見て身を引きます。

```dart
@Configuration()
class CacheSetup {
  // キャッシュスターター自身の CacheManager は生成されない。
  @Bean()
  CacheManager cacheManager() => InMemoryCacheManager(
    cacheNames: ['books', 'prices'],
    defaultSpec: const CacheSpec(timeToLive: Duration(minutes: 10)),
  );
}
```

Bean を置き換えると、その設定も置き換わります。`spring.cache.*` のプロパティは、もはや自分の `CacheManager` には適用されません。一つの詳細だけを変えて残りを保つには、多くのスターターが代わりにカスタマイザーの Bean を提供しています。JSON の場合:

```dart
@Configuration()
class JsonConfig {
  // 整形された JSON。Web スターターの応答にも Feign にも。
  @Bean()
  JsonMapperBuilderCustomizer indented() => JsonMapperBuilderCustomizer.of(
    (builder) => builder.enable(SerializationFeature.indentOutput),
  );
}
```

## 自動構成を除外する

スターターの Bean を一つも望まない場合は、その条件が実行される前にモジュールを除外します。

```dart
@SpringBootApplication(
  // 名前によるモジュール全体。
  excludeName: ['springBootStarterCacheAutoConfiguration'],
)
void main(List<String> args) => runApplication(args);
```

- `excludeName` は、モジュールの名前 (その `BeanModule` の名前) か、自動構成クラスの名前 (`JacksonAutoConfiguration`、またはその完全な名前) を受け取ります。未知の名前は無視されます。
- `exclude` は、`@AutoConfiguration` クラスで書かれたスターターのために、それらのクラスを型で受け取ります ([独自のスターター](your-own-starter.md) を参照)。自動構成でない型は起動を止めます。
- プロパティ `spring.autoconfigure.exclude` は両方に追加します: `spring.autoconfigure.exclude=JacksonAutoConfiguration`。

除外は起動時に働きます。モジュールのコードもアプリケーションにはコンパイルされます。詳しくは: [exclude と excludeName](../components/spring-core-dart-generator/spring-boot-application.md)。

## 一つの Environment

すべてのプロパティは一つの `Environment` にあり、誰にとっても同じソースから読まれます。`application.properties` や `application.yml` とそのプロファイルのファイル、作業ディレクトリやその `config/` フォルダーのファイル、環境変数、コマンドライン引数です。スターターの `@ConfigurationProperties` クラスは自分のものと同じようにそこからバインドされるので、すべてのキーをそれらのどの場所でも設定できます。

```yaml
# lib/resources/application.yml
server:
  port: 9000                         # Web スターター
spring:
  json:
    property-naming-strategy: SNAKE_CASE   # spring_boot_dart の ObjectMapper
  cache:
    type: simple                     # キャッシュスターター
logging:
  level:
    root: info                       # ロギングスターター
    spring.web: debug
shop:
  delivery-time: 2d                  # 自分の @ConfigurationProperties('shop')
```

Web スターターと Feign は `ObjectMapper` を共有しているので、`spring.json.property-naming-strategy: SNAKE_CASE` の一行で、コントローラーと Feign クライアントの JSON がまとめて変わります。

アクティブなプロファイルも共有されます。`--spring.profiles.active=prod` は、すべてのスターターについて `application-prod.yml` を読み、自分のコードの `@Profile(['prod'])` の Bean を切り替えます。詳しくは: [Environment](../components/spring-core-dart/config/environment.md)、[プロファイル](../components/spring-core-dart/config/profiles.md)。

## Spring (Java) との対応

モデルは Spring Boot のものです。一つのコンテキスト、アプリケーションの Bean の後の自動構成、`@ConditionalOnMissingBean` による身の引き方、`exclude` と `excludeName`、一つの `Environment` です。重要な違い:

- スターターは、起動時のクラスパスからではなく、ビルド時に `lib/spring_auto_configuration.dart` から見つけられます。スターターを追加したら再ビルドしてください。
- 順序付けの単位はモジュールです。`order`、`before`、`after` は `@AutoConfigurationModule` の引数で、クラスに付ける `@AutoConfigureOrder` や `@AutoConfiguration(before:, after:)` ではありません。
- `exclude` の `Type` は単純な名前で比較されます。
- `@ConditionalOnClass` はありません。依存関係のグラフとビルド条件がその役割を担います。

## 関連項目

- [スターター](starters.md)
- [独自のスターター](your-own-starter.md)
- [自動構成](../components/spring-core-dart-generator/auto-configurations.md)
- [BeanModule](../components/spring-core-dart/beans/bean-module.md)
