小编Gan*_*fIX的帖子

application.yaml 和属性中的 Spring 启动日期处理

我正在创建一个简单的 Spring Boot 应用程序,它从 application.yaml 文件加载一个字符串(ISO 日期),并尝试将其放入 @Value 带注释的字段中。如果我使用 .yaml 文件,则字符串显然会转换为日期/日历,然后“toStringed”转换为不同的格式。如果我使用 .properties 文件,则字符串按原样传递。

应用

@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);
        SampleComponent c = ctx.getBean(SampleComponent.class);
        c.bla();
    }
}
Run Code Online (Sandbox Code Playgroud)

需要配置的组件

@Component
public class SampleComponent {

     @Value("${dateString}")
     private String dateString;

     public void bla() {
        System.out.println(dateString);
     }
}
Run Code Online (Sandbox Code Playgroud)

应用程序.yaml

dateString: 2015-01-09
Run Code Online (Sandbox Code Playgroud)

=> 输出:2015 年欧洲中部时间 1 月 9 日星期五 01:00:00

应用程序属性

dateString=2015-01-09
Run Code Online (Sandbox Code Playgroud)

=> 输出:2015-01-09

对我来说,使用属性解决方案很好,但我不明白为什么会发生这种情况?

(注意:当尝试将 yaml-date 分配给日期字段时,出现预期的“无法将类型 [java.lang.String] 的值转换为所需类型 [java.util.Date]:找不到匹配的编辑器或转换策略”异常被抛出)

configuration yaml date spring-boot

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

configuration ×1

date ×1

spring-boot ×1

yaml ×1