Spring 3中如何注册GenericConverter供SimpleJdbcCall使用?
问题:Spring 3.0.x中SimpleJdbcCall无法使用自定义GenericConverter转换强类型ID
场景说明
在Spring 3.0.x环境下,我通过SimpleJdbcCall配合BeanPropertyRowMapper进行数据库操作。现在需要把实体中原本用java.lang.Long类型的ID替换为强类型ID:定义了PersonId类,内部用Long变量存储实际ID值。
为了实现JDBC返回的BigDecimal到PersonId的转换(同时支持其他强类型ID的转换),我实现了org.springframework.core.convert.converter.GenericConverter接口,并通过以下XML配置注册转换器:
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="xxx.impl.IDTypeConverter"/> </set> </property> </bean>
遇到的问题
Spring并没有使用我注册的转换器。调试时发现,在org.springframework.beans.TypeConverterDelegate.convertIfNecessary(String, Object, Object, Class, TypeDescriptor)方法中,this.propertyEditorRegistry.getConversionService()返回null,导致转换逻辑根本没执行。
已尝试的方向与困境
- 看到有资料指出Spring会优先查找注册到PropertyEditor的自定义转换器,但没有给出具体实现步骤;
- 另一个方案提到使用(Abstract)JdbcConfiguration中的
jdbcCustomConversions()方法,但我的项目里找不到这些类; - 虽然可以为每个JDBC调用编写自定义RowMapper,但会产生大量重复代码,不符合最少代码的需求。
求问:如何用最少的代码实现这类数据类型的转换?
内容的提问来源于stack exchange,提问作者David Balažic
相关产品推荐
相关产品推荐

