此版本仍在开发中,尚未被视为稳定版。如需最新稳定版本,请使用 Spring Modulith 2.0.4spring-doc.cadn.net.cn

时刻 — 时间事件传递 API

spring-modulith-moments 是一个“时间流逝事件”的实现,其灵感强烈来源于 Matthias Verraes 的博客文章。 它是一种基于事件的时间处理方法,用于触发与特定时间段流逝相关联的操作。spring-doc.cadn.net.cn

要使用此抽象,请在您的项目中包含以下依赖项:spring-doc.cadn.net.cn

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

添加到项目类路径的依赖项会导致您的应用程序发生以下情况:spring-doc.cadn.net.cn

  • 应用程序代码可以在 Spring 事件监听器中引用 HourHasPassedDayHasPassedWeekHasPassedMonthHasPassedQuarterHasPassedYearHasPassed 类型,以便在经过特定时间后收到通知。spring-doc.cadn.net.cn

  • 类型为 org.springframework.modulith.Moments 的 Bean 在 ApplicationContext 中可用,其中包含触发这些事件的逻辑。spring-doc.cadn.net.cn

  • 如果将 spring.modulith.moments.enable-time-machine 设置为 true,该实例将成为一个 org.springframework.modulith.TimeMachine,从而允许“时间推移”,并触发所有中间事件。这对于集成测试由这些事件触发的功能非常有用。spring-doc.cadn.net.cn

默认情况下,Moments 使用一个 Clock.systemUTC() 实例。要自定义此配置,请声明一个类型为 Clock 的 Bean。spring-doc.cadn.net.cn

@Configuration
class MyConfiguration {

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

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

Moments 暴露了以下应用程序属性以进行高级定制:spring-doc.cadn.net.cn

表 1. 可用的应用程序属性
属性 默认值 描述

spring.modulith.moments.enable-time-machinespring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

如果设置为 true,则 Moments 实例将成为一个 TimeMachine,它提供用于将时间向前推移的 API。这对于期望由时间流逝事件触发功能的集成测试非常有用。spring-doc.cadn.net.cn

spring.modulith.moments.granularityspring-doc.cadn.net.cn

小时spring-doc.cadn.net.cn

触发事件的最小粒度。替代值 days 可避免每小时触发事件。spring-doc.cadn.net.cn

spring.modulith.moments.localespring-doc.cadn.net.cn

Locale.getDefault()spring-doc.cadn.net.cn

确定周边界时要使用的Localespring-doc.cadn.net.cn

spring.modulith.moments.quarter-start-monthspring-doc.cadn.net.cn

Months.JANUARYspring-doc.cadn.net.cn

季度开始的月份。spring-doc.cadn.net.cn

spring.modulith.moments.zone-idspring-doc.cadn.net.cn

ZoneOffset#UTCspring-doc.cadn.net.cn

ZoneId 用于确定附加到已发布事件的时间。spring-doc.cadn.net.cn