怎樣做網(wǎng)站服務(wù)器亞馬遜關(guān)鍵詞搜索工具
原文網(wǎng)址:SpringBoot--yml配置文件的時(shí)間/大小的單位轉(zhuǎn)換_IT利刃出鞘的博客-CSDN博客
簡(jiǎn)介
說明
本文介紹SpringBoot的yml(properties)配置文件的時(shí)間/大小的單位轉(zhuǎn)換。
概述
SpringBoot可以將yml中的配置綁定到一個(gè)Java類的字段,而且支持單位的轉(zhuǎn)換。以時(shí)間為例,yml中指定為2m,則可以用Duration來接收這個(gè)字段,接收到的字段值為3分鐘。
注意
本處的單位轉(zhuǎn)換支持配置放到一個(gè)類中,也支持@Value等。
時(shí)間的轉(zhuǎn)換
概述
Spring 使用 java.time.Duration 類代表時(shí)間大小,以下場(chǎng)景適用:
- 除非指定 @DurationUnit ,否則一個(gè) long 代表的時(shí)間為毫秒。
- ISO-8601 標(biāo)準(zhǔn)格式( java.time.Duration 的實(shí)現(xiàn)就是參照此標(biāo)準(zhǔn))
- 你也可以使用以下支持的單位(用大寫也可以):
- ns - 納秒
- us - 微秒
- ms - 毫秒
- s - 秒
- m - 分
- h - 時(shí)
- d - 天
示例
application.yml
custom:monitor:name: myMonitorinterval: 3m
實(shí)體類
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();}
}
測(cè)試類
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";}
}
測(cè)試
打個(gè)斷點(diǎn),然后請(qǐng)求:
工具類實(shí)例
SpringBoot的轉(zhuǎn)換時(shí)間的工具類是: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)}
}
大小的轉(zhuǎn)換
上邊是文章部分內(nèi)容,為便于維護(hù),全文已轉(zhuǎn)移到此網(wǎng)址:SpringBoot-yml配置文件的時(shí)間/大小的單位轉(zhuǎn)換 - 自學(xué)精靈