【发布时间】:2018-03-05 14:14:02
【问题描述】:
是否可以将 SpringBoot 从属性文件中读取的配置属性转换为特定的类? 例如,拥有一个属性
myClass = xx.abc.MyClass
在我的配置类中,我想要类似的东西:
private Class myClass = xx.abc.MyClass.class;
【问题讨论】:
标签: class spring-boot casting properties configuration
是否可以将 SpringBoot 从属性文件中读取的配置属性转换为特定的类? 例如,拥有一个属性
myClass = xx.abc.MyClass
在我的配置类中,我想要类似的东西:
private Class myClass = xx.abc.MyClass.class;
【问题讨论】:
标签: class spring-boot casting properties configuration
我通过添加自定义转换器解决了这个问题。 Using Type Converters With Spring MVC帮我找到了解决办法:
import org.springframework.core.convert.converter.Converter;
public class StringToClassConverter implements Converter<String, java.lang.Class> {
@Override
public Class convert(final String source) {
try {
return Class.forName(source);
} catch (ClassNotFoundException cnfEx) {
// Handle exception properly however you want to...
cnfEx.printStackTrace();
}
return null;
}
}
你的 SpringBoot 主类让扩展 WebMvcConfigurerAdapter 并实现和实现 WebMvcConfigurerAdapter 的 register 方法:
@Override
public void addFormatters(final FormatterRegistry registry) {
registry.addConverter(new StringToClassConverter());
}
更新:
SpringBoot 有它自己的能力,似乎最好以这种方式实现目标:
或
@见
Spring Boot - Custom Type Conversion with @ConfigurationProperties
和
Spring Boot - Type safe properties binding with @ConfigurationProperties
就是这样! :-)
如果 Spring 能够提供开箱即用的基本转换器,那就太好了。
【讨论】: