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。

相关推荐
用户8307196840824 分钟前
Java 告别繁琐数据统计代码!MySQL 8 窗口函数真香
java·sql·mysql
小林coding19 分钟前
专为程序员打造的简历模版来啦!覆盖前端、后端、测开、大模型等专业简历
前端·后端
UrbanJazzerati30 分钟前
当网页翻页时,页码藏在哪里?——一次对分页机制的解密之旅
后端·面试
用户44904120955631 分钟前
一次生产环境下的Redis连接耗尽问题排查与解决全过程
后端
Tapir36 分钟前
被 Karpathy 下场推荐的 NanoClaw 是什么来头
前端·后端·github
带刺的坐椅38 分钟前
SolonCode v0.0.20 发布 - 编程智能体(新增子代理和浏览器能力)
java·ai·agent·solon·solon-ai·claude-code·openclaw
ssshooter2 小时前
Tauri 项目实践:客户端与 Web 端的授权登录实现方案
前端·后端·rust
代码搬运媛2 小时前
Go 语言通道 (Channel) 深度用法讲解及实战
后端·go
会员源码网2 小时前
数字格式化陷阱:如何优雅处理 NumberFormatException
java
程序员爱钓鱼2 小时前
Go生成唯一ID的标准方案:github.com/google/uuid使用详解
后端·google·go