spring boot yaml文件中如何设置duration对象值

Spring Boot对表示持续时间有专门的支持。如果您公开java.time.Duration属性,则应用程序对应Duration类型的属性有以下格式可用:

  • long类型的常规表示(使用毫秒作为默认单位,除非指定了@DurationUnit)
  • java.time.Duration 使用的标准ISO-8601格式
  • 其中值和单位是耦合的,一种更可读的格式(例如:10s表示10秒)

什么意思呢,举例:

java 复制代码
@ConfigurationProperties(prefix = "spring.converting.durations")
public class DurationsProperties {
    
    /**
     * 使用了@DurationUnit注解,单位(秒)
     */
    @DurationUnit(ChronoUnit.SECONDS)
    private Duration unitDuration;

    /**
     * 默认毫秒
     */
    private Duration millisecond;

    /**
     * 值和单位是耦合的
     */
    private Duration formatDuration;
 	// ... get/set方法
}
yaml 复制代码
spring:
  converting:
    durations:
      millisecond: 5000
      unitDuration: 50
      formatDuration: 1h

如上代码所示,假设应用已启动,并成功给对象DurationsProperties 属性匹配好了值,那么unitDuration的值就代表50秒,millisecond的值就代表5000毫秒(5秒),formatDuration的值代表1小时(3600秒),从下面的截图也可看出,Duration默认单位是毫秒。

持续时间单位有:

单位 表示
ns 纳秒
us 微秒
ms 毫秒
s
m 分钟
h 小时
d

具体更多内容可参考官网地址:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.typesafe-configuration-properties.conversion.durations。

相关推荐
RoyLin17 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在18 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit18 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言
Goland猫18 小时前
电商架构图
后端
Java中文社群18 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
我是天龙_绍18 小时前
Whisper 通过 mp3输出中文
后端
zjjuejin18 小时前
Maven环境搭建
后端·maven
我是天龙_绍18 小时前
项目根目录有requirements.txt 如何安装
后端
bobz96518 小时前
MPLS VPN | SRV6 TE 安全隔离路由技术
后端
bobz96519 小时前
AMD 正式停更 AMDVLK 驱动: 有格局的厂商和社区会是一致的
后端