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。

相关推荐
张柏慈10 分钟前
Java性能优化:实战技巧与案例解析
java
天“码”行空15 分钟前
简化Lambda——方法引用
java·开发语言
带刺的坐椅1 小时前
MCP 进化:让静态 Tool 进化为具备“上下文感知”的远程 Skills
java·ai·llm·agent·solon·mcp·tool-call·skills
java1234_小锋1 小时前
Java线程之间是如何通信的?
java·开发语言
张张努力变强1 小时前
C++ Date日期类的设计与实现全解析
java·开发语言·c++·算法
while(1){yan}2 小时前
Spring事务
java·数据库·spring boot·后端·java-ee·mybatis
毕设源码-赖学姐2 小时前
【开题答辩全过程】以 高校社团管理平台为例,包含答辩的问题和答案
java
余瑜鱼鱼鱼3 小时前
线程和进程的区别和联系
java·开发语言·jvm
小唐同学爱学习3 小时前
如何解决海量数据存储
java·数据库·spring boot·mysql