Spring配置属性转换:如何让自定义Converter生效生成子类实例
解决方案
问题根源
你的转换器未被调用,核心原因是泛型参数不匹配:Spring解析配置时,会把每个自定义字段节点先转换成Map<String, Object>,而非你定义的Map<String, CustomField>,导致你的转换器无法被Spring识别触发。
修正步骤
1. 调整转换器泛型与实现逻辑
修改转换器的源类型为Map<String, Object>,并实现根据type字段创建对应子类的逻辑,同时利用Spring的BeanWrapper自动填充属性,避免手动赋值的繁琐:
@Component @ConfigurationPropertiesBinding public class CustomFieldConverter implements Converter<Map<String, Object>, CustomField> { @Override public CustomField convert(Map<String, Object> source) { String type = (String) source.get("type"); CustomField customField = switch (type) { case "string" -> new CustomFieldString(); case "number" -> new CustomFieldNumber(); case "boolean" -> new CustomField(); // 也可单独创建CustomFieldBoolean子类 default -> throw new IllegalArgumentException("不支持的自定义字段类型: " + type); }; // 自动填充所有属性(含父类的type、i18nKey) BeanWrapper wrapper = new BeanWrapperImpl(customField); source.forEach(wrapper::setPropertyValue); return customField; } }
2. 修正配置拼写错误
你的YAML配置中minLenght、maxLenght存在拼写错误,需改为minLength、maxLength,否则CustomFieldString的对应属性无法被正确绑定:
spring: application: name: spring-config-converter org.example: account: customFields: booleanTest: type: boolean i18nKey: "org.example.customField.boolean" stringTest: type: string i18nKey: "org.example.customField.string" minLength: 1 maxLength: 3 numberTest: type: number i18nKey: "org.example.customField.number" decimalDigits: 2
3. 确保配置类生效
在主启动类或配置类上添加@EnableConfigurationProperties(CustomConfig.class),确保配置属性绑定逻辑被Spring启用:
@SpringBootApplication @EnableConfigurationProperties(CustomConfig.class) public class SpringConfigConverterApplication { public static void main(String[] args) { SpringApplication.run(SpringConfigConverterApplication.class, args); } }
验证效果
应用启动后,CustomConfig中的account.customFields会被正确解析为对应子类实例:
booleanTest为CustomField实例stringTest为CustomFieldString实例,包含正确的minLength和maxLength值numberTest为CustomFieldNumber实例,包含正确的decimalDigits值
内容的提问来源于stack exchange,提问作者Christian
相关产品推荐
相关产品推荐

