我有一个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。
答案 0 :(得分:1)
要解决您的直接问题,您需要查看bean上的@PostConstruct
选项。这将允许您在bean可用于上下文之前对事物采取行动。
@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}")
private String customFieldType;
private CustomInterface customField;
@PostConstruct
public void init() {
customField = (CustomInterface) Class.forName(customFieldType).newInstance(); // short form... will need checks that it finds the class and can create a new instance
}
}
class CustomType implements CustomInterface {...}
interface CustomInterface {...}
我很好奇你是否想在类上使用@Configuration
注释并创建一个在Spring ApplicationContext上作为bean提供的CustomInterface
实例。要做到这一点,你会做这样的事情:
@Component
@ConfigurationProperties(prefix = "prefix")
class MySettings {
private int intField;
private String stringField;
private String customTypeField;
// getters and setters
}
然后将在@Configuration
类中使用:
@Configuration
class MyConfiguration {
@Bean
public CustomInterface customInterface(MySettings mySettings) {
return (CustomInterface) Class.forName(mySettings.getCustomTypeField()).newInstance();
}
}
此时您将拥有CustomInterface
的实例化bean,您可以将Spring自动装配到其他对象中。