Spring boot配置文件属性转换

在我们用Springboot进行开发的时候,我们的很多可配置化的参数会写在配置文件内,然后可以用 @ConfigurationProperties 将其转化为bean在程序中使用。在转化为bean时,Springboot会默认给我提供一系列的Converter进行参数的转化。如字符串和数据类型的转换,Duration和对应字符串的转换等等。但是有时候一些类型的转换springboot并没有提供对应的Converter,那么我们可以自定义,具体见下文。

这周我想在application.yml文件中配置一个工作时间的时间段,比如9:30-18:30,想转化为 LocalTime,但是发现行不通。具体如下:

一 问题代码

application.yml

demo:
  startTime: "09:30:00"
  timeout: 2m

ConfigProperties.java

@Data
@Component
@ConfigurationProperties(prefix = "demo")
public class ConfigProperties {
    private LocalTime startTime;
    private Duration timeout;
}

启动报错

***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'demo.start-time' to java.time.LocalTime:
    Property: demo.starttime
    Value: 09:30:00
    Origin: class path resource [application.yml]:2:14
    Reason: failed to convert java.lang.String to java.time.LocalTime
Action:
Update your application's configuration

解决报错

首先,当然我们可以用String来接 startTime 的值,然后在代码中自己在将其转为LocalTime,这样做也行,但是会存在一个问题,如果我不小心将 startTime 的值配置错了,比如配成了”08:3o:00”(其中一个0配置了字母o)。这时程序启动是不会报错的,只有程序运行到你的转换代码才会报错,我们需要避免在系统运行时才发现错误,防止对应的生产问题。

既然错误提示已经给出无法将String转为LocalTime,那么我们可以自定义Converter,只需要两步:

  1. 实现 Converter 接口
  2. @ConfigurationPropertiesBinding 注册自定义的 Converter

自定义 Converter

import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
import java.util.Objects;
@Component
@ConfigurationPropertiesBinding
public class LocalTimeConverter implements Converter<String, LocalTime> {
    @Override
    public LocalTime convert(String source) {
        Objects.requireNonNull(source);
        return LocalTime.parse(source);
    }
}

好了,万事俱备,启动程序

2019-08-17 17:23:39.902  INFO 27553 --- [on(2)-127.0.0.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-08-17 17:23:39.902  INFO 27553 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-08-17 17:23:39.912  INFO 27553 --- [on(2)-127.0.0.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 9 ms

大公告成,遇到相同问题的朋友可以自己动手实现自己的Converter了。


原文:https://justsme.github.io/2019/08/17/Spring-boot配置文件属性转换/
作者:justsme

学会了