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。

相关推荐
Carsene几秒前
Spring Boot 包扫描新姿势:AutoScan vs @Import vs @ComponentScan 深度对比
spring boot·后端
Gopher_HBo2 分钟前
ReentrantReadWriteLock源码讲解
java·后端
文浩AI3 分钟前
Claude Code 创始人 Boris Cherny 的并行工作流最佳实践
后端
农村小镇哥4 分钟前
PHP数据传输流+上传条件+上传步骤
java·开发语言·php
wuxinyan1235 分钟前
Java面试题48:一文深入了解java设计模式
java·设计模式·面试
武子康9 分钟前
大数据-267 实时数仓-架构演进:Lambda与Kappa架构实战指南
大数据·后端
济源IT小伙一枚10 分钟前
⚡️硬核实战:Spring AI + Ollama 从零搭建私有化多角色 AI 助手|RAG 知识库 + MCP 控制台全实现
java·人工智能·spring
苏三说技术11 分钟前
Java程序员必看的RAG入门教程
后端
李少兄11 分钟前
Windows 安装 Maven 详细教程(含镜像与本地仓库配置)
java·windows·maven
yongyoudayee12 分钟前
2026中国企业出海CRM:五大平台技术能力对比
后端·python·flask