【发布时间】:2023-03-29 08:50:01
【问题描述】:
我有一个依赖 jar,它在 yaml 中配置了如下值:
app:
settings:
value1 : true
而java代码是
public class LoadConfig {
@Value("${app.settings.value1}")
private Boolean value1;
}
在部署 Spring Boot 应用程序时,在运行时,依赖项 jar 值未解析,出现以下问题。
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'LoadConfig':
Unsatisfied dependency expressed through field 'value1'; nested exception is
org.springframework.beans.TypeMismatchException:**Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'**; nested
exception is java.lang.IllegalArgumentException: Invalid boolean value [**${app.settings.value1}**].
问题不是 value,而是 path(app.settings.value1) 被转换为 Boolean 并引发错误。
maven项目结构是
MyJar --> app.jar
|-> dependency.jar
【问题讨论】:
-
你能不能把 yaml 格式化好一点
-
对于非字符串值,可以试试@Value("#{new Boolean('${app.settings.value1}")
-
@Value("#{new Boolean('${app.settings.value1:true}") OR @Value("'${app.settings.value1}") private boolean value1 ; //注意原语的使用
-
您共享的链接试图将 1 转换为布尔值,在我的情况下,它没有读取值,它正在尝试转换 @Value("") 中存在的任何内容。跨度>
-
请注意,在 Boot 中,
@ConfigurationProperties类几乎总是优于@Value。
标签: java spring spring-boot spring-annotations