【发布时间】:2017-02-26 02:51:43
【问题描述】:
我有一个 myapp.properties 文件,其键值对定义为:
prefix.int-field=123
prefix.string-field=asdf
prefix.custom-type-field=my.package.CustomType
我正在尝试通过在以下类中使用 @Value 注释来注入这些属性:
@PropertySource(value = "classpath:myapp.properties")
@Component
class MySettings {
@Value("${prefix.int-field}")
private int intField;
@Value("${prefix.string-field}")
private String stringField;
@Value("${prefix.custom-type-field}") // <-- this is the problem
private CustomInterface customField;
}
class CustomType implements CustomInterface {...}
interface CustomInterface {...}
现在,intField 和 stringField 按预期使用所需的值进行初始化,但 customField 抛出异常:
Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [my.package.CustomInterface]: no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:303) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:125) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:61) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
如何将文本属性值转换为我的自定义类型?
我试图咨询documentation,但我看不到正确的做法。我正在使用 Spring Boot 1.3.6。
【问题讨论】:
-
您是否尝试过添加您的自定义转换器?应该是实现Converter
的类,更多详情stackoverflow.com/questions/34239585/… -
你为什么不把它像豆子一样注入?
-
@freakman 我还没有尝试过,我是 Spring 新手,对事情感到困惑。我试试看
-
@grape_mao 但我希望
customField可以通过属性文件进行配置,也就是说,如果我以后选择使用CustomInterface的不同实现,我可以只更改属性文件...
标签: java spring spring-boot type-conversion properties-file