Class 我可以使用SpringBoot配置在属性文件中强制转换值吗?

Class 我可以使用SpringBoot配置在属性文件中强制转换值吗?,class,spring-boot,casting,properties,configuration,Class,Spring Boot,Casting,Properties,Configuration,是否可以将SpringBoot从属性文件读取的配置属性强制转换为特定类? 例如,拥有一个财产 myClass = xx.abc.MyClass 在我的配置类中,我希望有如下内容: private Class myClass = xx.abc.MyClass.class; 我通过添加自定义转换器解决了这个问题。帮助我找到解决方案: import org.springframework.core.convert.converter.Converter; public class StringT

是否可以将SpringBoot从属性文件读取的配置属性强制转换为特定类? 例如,拥有一个财产

myClass = xx.abc.MyClass
在我的配置类中,我希望有如下内容:

private Class myClass = xx.abc.MyClass.class;

我通过添加自定义转换器解决了这个问题。帮助我找到解决方案:

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有自己的功能,通过以下方式实现目标似乎更好:


  • @组件和
    @ConfigurationPropertiesBinding注释转换器
  • 将@EnableConfigurationProperties(MyAppProperties.class)与@SpringBootApplication一起使用
  • @见


    就这样!:-)

    如果Spring能够提供这种开箱即用的基本转换器,那就太好了

    @Override
    public void addFormatters(final FormatterRegistry registry) {
        registry.addConverter(new StringToClassConverter());
    }