Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom converter with Spring dependency injection

Tags:

spring

dozer

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?

like image 491
Thilo-Alexander Ginkel Avatar asked Oct 21 '25 23:10

Thilo-Alexander Ginkel


1 Answers

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>
like image 163
Chris Koele Avatar answered Oct 25 '25 06:10

Chris Koele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!