怎樣做網(wǎng)站服務器亞馬遜關鍵詞搜索工具
原文網(wǎng)址:SpringBoot--yml配置文件的時間/大小的單位轉換_IT利刃出鞘的博客-CSDN博客
簡介
說明
本文介紹SpringBoot的yml(properties)配置文件的時間/大小的單位轉換。
概述
SpringBoot可以將yml中的配置綁定到一個Java類的字段,而且支持單位的轉換。以時間為例,yml中指定為2m,則可以用Duration來接收這個字段,接收到的字段值為3分鐘。
注意
本處的單位轉換支持配置放到一個類中,也支持@Value等。
時間的轉換
概述
Spring 使用 java.time.Duration 類代表時間大小,以下場景適用:
- 除非指定 @DurationUnit ,否則一個 long 代表的時間為毫秒。
- ISO-8601 標準格式( java.time.Duration 的實現(xiàn)就是參照此標準)
- 你也可以使用以下支持的單位(用大寫也可以):
- ns - 納秒
- us - 微秒
- ms - 毫秒
- s - 秒
- m - 分
- h - 時
- d - 天
示例
application.yml
custom:monitor:name: myMonitorinterval: 3m
實體類
package com.knife.config;import lombok.Data;import java.time.Duration;@Data
public class MonitorProperty {private String name;private Duration interval;
}
配置類
package com.knife.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MonitorConfig {@ConfigurationProperties(prefix = "custom.monitor")@Beanpublic MonitorProperty monitorProperty() {return new MonitorProperty();}
}
測試類
package com.knife.controller;import com.knife.config.MonitorProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@Autowiredprivate MonitorProperty monitorProperty;@GetMapping("/test")public String test() {return "test success";}
}
測試
打個斷點,然后請求:
工具類實例
SpringBoot的轉換時間的工具類是:DurationStyle(org.springframework.core.convert.support包)。
示例:
import org.springframework.core.convert.support.DurationStyle;
import java.time.Duration;public class MyApp {public static void main(String[] args) {String durationString = "3m";Duration duration = DurationStyle.SIMPLE.parse(durationString);System.out.println(duration); // 輸出 PT3M (3 minutes)}
}
大小的轉換
上邊是文章部分內(nèi)容,為便于維護,全文已轉移到此網(wǎng)址:SpringBoot-yml配置文件的時間/大小的單位轉換 - 自學精靈