我们无法在 Spring Boot 中使用 java.util.Duration 作为 @Value 配置。
此处展示此问题的示例项目:https://github.com/costimuraru/spring-boot-sample https://github.com/costimuraru/spring-boot-sampleSpring 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:注入自动装配
依赖失败;嵌套异常是
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 表达式语言
@Value("#{T(java.time.Duration).parse('${mykey}')}")
private Duration value;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)