Spring Boot 自定义属性转换器的核心是通过@ConfigurationPropertiesBinding注解让Spring自动发现并使用Converter,实现YAML/Properties字符串到Java类型的转换;例如将"com.example.ServiceA"转为Class类型,并在@ConfigurationProperties配置类中自动生效。

Spring Boot 自定义属性转换器,核心是让 @ConfigurationProperties 能正确把 YAML 或 Properties 中的字符串(比如类名、JSON 片段、自定义格式)转成你想要的 Java 类型(如 Class>、Map、业务对象等)。关键不在于“写个转换逻辑”,而在于让 Spring 在配置绑定阶段**自动发现并使用它**。
用 @ConfigurationPropertiesBinding 注册全局转换器
这是最常用、也最推荐的方式,专为 @ConfigurationProperties 设计:
- 实现
Converter接口,比如把字符串转成Class>或自定义的Rule对象 - 加上
@Component和@ConfigurationPropertiesBinding两个注解 - Spring Boot 启动时会自动将它注册进配置绑定的转换服务,无需手动注入或配置
示例:将 com.example.ServiceA 这样的字符串转成 Class>
@Component
@ConfigurationPropertiesBinding
public class ClassConverter implements Converter<string class>> {
@Override
public Class> convert(String source) {
if (source == null || source.trim().isEmpty()) return null;
String className = source.trim().replaceFirst("\.class$", "");
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("无法加载类: " + className, e);
}
}
}</string>
⚠️ 注意:Class.forName() 必须传全限定名;如果 YAML 写的是 a.class,转换器里要先去掉 .class 后缀。
配合 @ConfigurationProperties 使用
转换器生效的前提,是你在配置类上用了 @ConfigurationProperties,且字段类型正好匹配转换目标:
- YAML 示例:
app:
handlers:
email: com.example.EmailHandler
sms: com.example.SmsHandler.class
- Java 配置类:
@ConfigurationProperties("app")
@Data
public class AppProperties {
private Map<string class>> handlers;
}</string>
只要 ClassConverter 存在且带正确注解,Spring 就会在绑定 handlers 字段时自动调用它。
其他方式(按需选用)
不是所有场景都适合用 @ConfigurationPropertiesBinding:
-
Web 层参数转换(比如 Controller 方法入参):用
WebMvcConfigurer.addFormatters()注册Converter,作用于 HTTP 请求数据绑定 -
通用类型转换服务(跨多个模块复用):定义一个名为
conversionService的ConversionServiceBean,但要注意它启动早、依赖受限 -
老式 PropertyEditor:已不推荐,仅兼容遗留代码;需实现
PropertyEditorSupport并通过CustomEditorConfigurer注册
多数配置类场景,坚持用 @ConfigurationPropertiesBinding 最简洁、最安全。











