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。

相关推荐
码出财富1 天前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
我是小疯子661 天前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
森叶1 天前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
二哈喇子!1 天前
Eclipse中导入外部jar包
java·eclipse·jar
微露清风1 天前
系统性学习C++-第二十二讲-C++11
java·c++·学习
进阶小白猿1 天前
Java技术八股学习Day20
java·开发语言·学习
gis开发1 天前
【无标题】
java·前端·javascript
Wpa.wk1 天前
性能测试 - 搭建线上的性能测试环境参考逻辑图
java·经验分享·测试工具·jmeter·性能测试
代码村新手1 天前
C++-类和对象(中)
java·开发语言·c++
葵花楹1 天前
【JAVA课设】【游戏社交系统】
java·开发语言·游戏