Spring Boot 中 yaml 文件中数字类型的 @Value [英] @Value for numeric types in yaml file in Spring Boot

查看:89
本文介绍了Spring Boot 中 yaml 文件中数字类型的 @Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下结构的资源文件夹中得到了一个 data.yml:

I got a data.yml in resources folder of a following structure:

main:
  header:
    info: 3600L

我使用 Spring Boot 2.4.2 版,我想将属性 main.header1.info 注入到一个字段中,我这样做了:

I use Spring Boot version 2.4.2, I want to inject property main.header1.info to a field, I do this the following way:

@Component
@PropertySource("classpath:data.yml")
public class SomeClass {
    @Value("`main.header1.info")
    private long info;
    ...
}

但是发生了 NumberFormatException:

java.lang.NumberFormatException: For input string: "main.header1.info"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:na]
    at java.base/java.lang.Long.parseLong(Long.java:692) ~[na:na]
    ...

我知道 yml 不支持 long,但我认为事实并非如此.我尝试了其他数字类型和相应的包装类,例如 Double.那么,如何解决这个问题?

I know that long is not supported in yml, but I think its not the case. I tried other numeric types and corresponding wrapper-classes, like Double. So, how to fix that?

推荐答案

我建议使用 application.yml 文件,尽管自定义 YAML 文件.

I recommend using application.yml file inspite of custom YAML file.

原因:application.properties 是 spring 的默认配置文件.如果你使用它,你就不必担心将文件加载到上下文手动,因为 spring 会处理它.但是,在你的情况下,你是尝试从自定义 YAML 文件加载和读取值.所以,@PropertySource 在这里没有帮助.

Reason : application.properties is spring's default config file. If you use it, you don't have to worry about loading the file to context manually as spring takes care of it. But, In you case, you are trying to load and read value from a custom YAML file. So, @PropertySource won't help here.

参考spring-docs 了解有关 YAML 缺点的详细信息.

Refer to the spring-docs for details about YAML Shortcomings.

但是,如果您仍然希望从自定义 yaml 中读取值,您将需要编写一个自定义类(例如:CustomYamlPropertySourceFactory)来实现 PropertySourceFactory &通知 @PropertySource 使用这个工厂类.

However if you still wish to read values from a custom yaml, You will need to write a custom class ( Ex : CustomYamlPropertySourceFactory ) which implements PropertySourceFactory & inform @PropertySource to use this factory class.

参考代码:

    @Component
    @PropertySource(value = "classpath:date.yml", factory = CustomYamlPropertySourceFactory.class) 
    public class SomeClass {

    @Value("${main.header.info}")
    private int info;
}

这篇关于Spring Boot 中 yaml 文件中数字类型的 @Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆