Custom converter with Spring dependency injection

Thilo-Alexander Ginkel picture Thilo-Alexander Ginkel · Jul 14, 2011 · Viewed 12.7k times · Source

Is there a way to define a custom converter in Dozer for converting one top-level type to another, which is itself a Spring bean and thus can get its dependencies injected?

The dozer docs propose to add the following XML definition:

  <converter type="org.dozer.converters.TestCustomConverter" >
    <class-a>org.dozer.vo.CustomDoubleObject</class-a>
    <class-b>java.lang.Double</class-b>
  </converter>

Unfortunately, this causes Dozer to instantiate org.dozer.converters.TestCustomConverter directly, which will skip dependency injection. Is there a way to reference a Spring bean instead?

Answer

Chris Koele picture Chris Koele · Sep 9, 2011

Next to CustomConverterWithIds as in previous answer it is also possible to inject custom converters to override the converters defined in the configuration part in the mapping file. That way dozer will use the injected converter instead of instantiating one using the default constructor.

<bean id="dozerMapper" class="org.dozer.DozerBeanMapper" scope="singleton">
    <property name="mappingFiles">
        <list>
            <value><mapping-file-name1></value>
            <value><mapping-file-name2></value>
        </list> 
    </property>
    <property name="customConverters">
        <list>
            <ref bean="entityConverter"/>
        </list>
    </property>
</bean>

<configuration>
   <custom-converters>
     <converter type="my.domain.EntityConverter">
        <class-a>java.lang.Integer</class-a>
        <class-b>my.domain.MyEntity</class-b>
     </converter>
   <custom-converters>
</configuration>

<beans   .... >
   <bean id="entityConverter" class="my.domain.EntityConverter">
        <property ....
   </bean
</beans>