【问题标题】:Not able to use java.util.Duration as @Value configuration in Spring Boot无法在 Spring Boot 中使用 java.util.Duration 作为 @Value 配置
【发布时间】:2018-05-23 21:38:41
【问题描述】:

我们无法在 Spring Boot 中使用 java.util.Duration 作为 @Value 配置。

此处显示此问题的示例项目:https://github.com/costimuraru/spring-boot-sample Spring Boot 版本:1.5.9.RELEASE

@RestController
public class HelloController {

    @Value("${mykey}")
    Duration value;

    @RequestMapping("/")
    public String index() {
        return "Greetings at " + value;
    }

}

...

public class MyConfigPropertySource extends PropertySource {

    MyConfigPropertySource(String name) {
        super(name);
    }

    @Override
    public Object getProperty(String path) {
        return "mykey".equals(path) ? Duration.ofMinutes(1) : null;
    }
}

org.springframework.beans.factory.BeanCreationException: 错误 创建名为 'helloController' 的 bean:注入 autowired 依赖失败;嵌套异常是 org.springframework.core.convert.ConverterNotFoundException:否 发现能够从类型 [java.time.Duration] 转换的转换器 键入 [java.lang.String] 在 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE] 在 org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]

这个错误完全出乎意料:No converter found capable of converting from type [java.time.Duration] to type [java.lang.String]。我们既没有在@Value 字段中也没有在 PropertySource 的返回语句中使用 String。那么为什么 Spring Boot 试图将其转换为 String 呢?非常感谢任何帮助。

【问题讨论】:

  • 在任何人浪费时间试图回答这个问题之前,Spring Boot 的问题跟踪器上也有人询问并回答了这个问题:github.com/spring-projects/spring-boot/issues/11306。请不要这样交叉发帖。
  • @AndyWilkinson 我不知道有多少次我点击了与 spring 数据库问题相关的 stackoverflow first,我根本找不到这个交叉发布...我什至建议你用一个答案来回答你的评论——这样人们就知道去哪里找了。
  • 链接问题中的第一条评论:感谢您与我们联系,但感觉这是一个更适合 Stack Overflow 的问题。 ;)

标签: java spring-boot java-8


【解决方案1】:

只需使用 Spring 表达式语言

@Value("#{T(java.time.Duration).parse('${mykey}')}")
private Duration value;

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 2018-09-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多