我有一个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,更多详细信息http://stackoverflow.com/questions/34239585/how-to-register-custom-converters-in-spring-boot –
freakman
为什么你不只是注入它像一颗豆子? –
@freakman我还没有尝试过,我是新来的春天和困惑的事情。我会给它一个 – radoh