瞬間 — 時間の経過イベント API

spring-modulith-moments は、Matthias Verraes のブログ投稿 (英語) に大きく影響を受けた Passage of Time Events の実装です。これは、経過した特定の期間に関連付けられたアクションをトリガーする、時間に対するイベントベースのアプローチです。

抽象化を使用するには、プロジェクトに次の依存関係を含めます。

<dependency>
  <groupId>org.springframework.modulith</groupId>
  <artifactId>spring-modulith-moments</artifactId>
</dependency>
dependencies {
  implementation 'org.springframework.modulith:spring-modulith-moments'
}

プロジェクトのクラスパスに依存関係が追加されると、アプリケーションで次のような問題が発生します。

  • アプリケーションコードは、Spring イベントリスナーの HourHasPassedDayHasPassedWeekHasPassedMonthHasPassedQuarterHasPassedYearHasPassed 型を参照して、一定の時間が経過した場合に通知を受け取ることができます。

  • org.springframework.modulith.Moments 型の Bean は、これらのイベントをトリガーするロジックを含む ApplicationContext で使用できます。

  • spring.modulith.moments.enable-time-machine が true に設定されている場合、そのインスタンスは org.springframework.modulith.TimeMachine となり、時間を「シフト」することができ、それによってすべての中間イベントをトリガーできます。これは、イベントによってトリガーされる統合テスト機能に役立ちます。

デフォルトでは、Moments は Clock.systemUTC() インスタンスを使用します。これをカスタマイズするには、Clock 型の Bean を宣言します。

  • Java

  • Kotlin

@Configuration
class MyConfiguration {

  @Bean
  Clock myCustomClock() {
    // Create a custom Clock here
  }
}
@Configuration
class MyConfiguration {

  @Bean
  fun myCustomClock(): Clock {
    // Create a custom Clock here
  }
}

Moments は、高度なカスタマイズのために次のアプリケーションプロパティを公開します。

表 1: 利用可能なアプリケーションのプロパティ
プロパティ デフォルト値 説明

spring.modulith.moments.enable-time-machine

false

true に設定すると、Moments インスタンスは TimeMachine となり、時間を前方にシフトする API を公開します。時間経過イベントによってトリガーされる機能を期待する統合テストに役立ちます。

spring.modulith.moments.granularity

時間

発生するイベントの最小粒度。毎時イベントを回避するための代替値 days

spring.modulith.moments.locale

Locale.getDefault()

週の境界を決定するときに使用する Locale

spring.modulith.moments.quarter-start-month

Months.JANUARY

四半期が始まる月。

spring.modulith.moments.zone-id

ZoneOffset#UTC

ZoneId は、発行されたイベントに関連付けられた時間を決定します。