简体   繁体   English

如何使用Spring转换服务将字符串值从属性文件自动转换为其他数据类型,即持续时间?

[英]How to auto convert string values from properties files to other data types i.e. duration using spring conversion service?

How to auto convert string values from properties files to other data types ie duration using spring conversion service? 如何使用Spring转换服务将字符串值从属性文件自动转换为其他数据类型,即持续时间?

properties file 属性文件

my.duration=PT10M

configuration class 配置类

@Value("{my.duration}")
//It'll give string value by default but I want to convert to duration
private Duration myDuration;

How can I achieve that using spring ConversionService ? 如何使用spring ConversionService实现该目标?

Here you can use YAML, if you want to populate a class with the values from resource files. 如果要使用资源文件中的值填充类,则可以在此处使用YAML。

Duration.yaml 持续时间

duration:
    val1: "PT"
    val2: "10"
    val3: "M"

Duration.java 持续时间

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "duration")
public class Duration {
    private String val1;
    private String val2;
    private String val3;

    // setters and getters.
}       

You can play around with this approach to get the desired output. 您可以使用这种方法来获得所需的输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Apache Commons Configuration对属性文件中的值列表进行变量插值,即$ {variable} - Using Apache Commons Configuration to do variable interpolation, i.e. ${variable}, with a list of values in a properties file 我们可以用大小不同的其他行(即新字符串)替换文件中的行吗? - Can we replace a line from file with other line (i.e. new string) having different size? 如何从 Java Spring 项目中的 application.properties 以外的配置文件中获取值 - How to pick up values from config files other than application.properties in Java Spring project Spring Data Mongo:如何仅保存日期,即不保存时间 - Spring Data Mongo: How to save only date i.e. not time 如何比较应具有 3 个值的 100 个字符串记录,即 true、False 或 null - How to Compare 100 String records which should have either 3 values i.e. true,False or null 如何使用 Spring 从属性文件中读取 - How to read from a properties files using Spring 是否可以动态加载包中包含的所有属性文件? 即MyClass.class.getResource('*。properties'); - Is it possible load all properties files contained in a package dynamically? i.e. MyClass.class.getResource('*.properties'); 如何创建并使用字符串作为输入输出Date对象? 即“ 13/04/1998” - How do I create and then output a Date object using a String as the input? i.e. “13/04/1998” 使用String的JAVA 2D地图? 即“ +”和“ C” - JAVA 2D Map using String? i.e. “+” and “C” 如何从Spring Boot Config Server服务的其他属性文件中的application.properties获取密钥? - How can I get the keys from application.properties within other properties files served by Spring Boot Config Server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM