【问题标题】:Can I cast a value in a properties file using SpringBoot configuration?我可以使用 Spring Boot 配置在属性文件中转换一个值吗?
【发布时间】:2018-03-05 14:14:02
【问题描述】:

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

myClass = xx.abc.MyClass

在我的配置类中,我想要类似的东西:

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

【问题讨论】:

    标签: class spring-boot casting properties configuration


    【解决方案1】:

    我通过添加自定义转换器解决了这个问题。 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 有它自己的能力,似乎最好以这种方式实现目标:

    1. 使用
      @Component 和
      @ConfigurationPropertiesBinding 注释转换器

    1. 将@EnableConfigurationProperties(MyAppProperties.class) 与@SpringBootApplication 一起使用

    @见
    Spring Boot - Custom Type Conversion with @ConfigurationProperties

    Spring Boot - Type safe properties binding with @ConfigurationProperties

    就是这样! :-)

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

    【讨论】:

      猜你喜欢
      • 2016-08-22
      • 2021-11-27
      • 1970-01-01
      • 2019-10-06
      • 2017-04-12
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      相关资源
      最近更新 更多