<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog4Java &#187; POJO</title>
	<atom:link href="http://malsolo.com/blog4java/?feed=rss2&#038;tag=pojo" rel="self" type="application/rss+xml" />
	<link>http://malsolo.com/blog4java</link>
	<description>A personal and Java blog, likely only for me</description>
	<lastBuildDate>Tue, 31 Mar 2015 15:52:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1.1</generator>
	<item>
		<title>Orika time!</title>
		<link>http://malsolo.com/blog4java/?p=465</link>
		<comments>http://malsolo.com/blog4java/?p=465#comments</comments>
		<pubDate>Thu, 23 Oct 2014 15:52:56 +0000</pubDate>
		<dc:creator><![CDATA[Javier (@jbbarquero)]]></dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Springsource]]></category>
		<category><![CDATA[Mapping]]></category>
		<category><![CDATA[Orika]]></category>
		<category><![CDATA[POJO]]></category>

		<guid isPermaLink="false">http://malsolo.com/blog4java/?p=465</guid>
		<description><![CDATA[I love good software, and Orika is a really interesting project. In this post I&#8217;m going to talk about this Java bean mapping framework that I&#8217;ve used recently and I highly recommend. Orika (formerly hosted at google code) claims to &#8230; <a href="http://malsolo.com/blog4java/?p=465">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I love good software, and Orika is a really interesting project. In this post I&#8217;m going to talk about this Java bean mapping framework that I&#8217;ve used recently and I highly recommend.</p>
<p><a href="http://orika-mapper.github.io/orika-docs/" title="Orika User Guide" target="_blank">Orika</a> (formerly hosted at <a href="https://code.google.com/p/orika/" title="Orika at google code" target="_blank">google code</a>) claims to be a <em>simpler, lighter and faster Java bean mapping</em>. And it really is.</p>
<p>It allows you to convert objects by copying its attributes from one to another. It performs this by using Java introspection, instead of XML configuration or something like that. It uses code generation to create the mappers, and it has an interesting strategy for its core classes that allows you to optimize the performance.</p>
<p>It is completely configurable, for instance, the java code generator by default is Javassist, but you can use EclipseJdt or even use another provider by implementing the appropriate interface.</p>
<p>Finally, it&#8217;s a very well documented project, with clear explanations and useful code.</p>
<p>I really like it.</p>
<p>If you want to try it, just add the next dependency to your maven project:</p>
<p></p><pre class="crayon-plain-tag">&lt;dependency&gt;
			&lt;groupId&gt;ma.glasnost.orika&lt;/groupId&gt;
			&lt;artifactId&gt;orika-core&lt;/artifactId&gt;
			&lt;version&gt;1.4.5&lt;/version&gt;&lt;!-- or latest version --&gt;
		&lt;/dependency&gt;</pre><p></p>
<p>Or <a href="https://github.com/orika-mapper/orika/releases" title="Orika releases at GitHub" target="_blank">download the library</a> along with three required libraries:</p>
<ul>
<li>javassist (v 3.12.0+)</li>
<li>slf4j (v 1.5.6+)</li>
<li>paranamer (v 2.0+)</li>
</ul>
<h1>Main concepts</h1>
<p>There are two core classes, the first one is <strong>MapperFactory</strong>, the class to configure the mappings and to obtain the second core class: <strong>MapperFacade</strong>, that actually provides the service of a Java bean mapping.</p>
<h3>MapperFactory</h3>
<p>By using a fluent API, you can construct a <strong>MapperFactory</strong> via its main implementation, <strong>DefaultMapperFactory</strong> and its static class helpers intended for building the <strong>MapperFactory</strong>.</p>
<p>Then you can obtain a <strong>ClassMapBuilder</strong> from the <strong>MapperFactory</strong> in order to declare the mapping configuration in a fluent-style, that is: mapping fields (bi-directional by default, or in one direction if you&#8217;d rather), excluding fields, specifying constructors and customizing mappings of Lists, Sets, nested fields and so on.</p>
<p>There is a default mapping that maps fields with matching names between two classes, and you can also register the mapping in the MapperFactory (the ClassMapBuilder is built with the very MapperFactory as atribute). Both operations have the appropriate methods to be called.</p>
<p>Let&#8217;s see an example:</p>
<p>We have two classes: <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/dto/PersonDTO.java" title="PersonDTO at github" target="_blank">PersonDTO</a> and <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/domain/Person.java" title="Person at github" target="_blank">Person</a>, and we want to convert one object for the former class to an object of the latter one, so let&#8217;s configure the MapperFactory:</p>
<p></p><pre class="crayon-plain-tag">MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
mapperFactory.classMap(PersonDTO.class, Person.class) //A ClassMapBuilder&lt;PersonDTO, Person&gt;
        .field(&quot;lastNames&quot;, &quot;surnames&quot;) //Register field mappings
        .field(&quot;streetAddress&quot;, &quot;address.street&quot;)
        .field(&quot;city&quot;, &quot;address.city&quot;)
        .field(&quot;postalCode&quot;, &quot;address.zipCode&quot;)
        .byDefault() //the remaining fields on both classes should be mapped matching the fields by name
        .register(); //register the mapping with the MapperFactory.</pre><p></p>
<p>The <strong>ClassMapBuilder</strong> provides interesting mappings for excluding fields, mapping fields in one direction only (as I mentioned above, mapping is by default bi-directional) and so on. See the <a href="http://orika-mapper.github.io/orika-docs/mappings-via-classmapbuilder.html" title="Declarative Mapping Configuration: using the fluent-style ClassMapBuilder API " target="_blank">Declarative Mapping Configuration</a> and <a href="http://orika-mapper.github.io/orika-docs/advanced-mappings.html" title="Advanced Mapping Configurations: beyond the basics of ClassMapBuilder API" target="_blank">Advanced Mapping Configurations</a> for more options.</p>
<h3>MapperFacade and BoundMapperFacade</h3>
<p>The <strong>MapperFacade</strong> performs the actual mapping work, for doing so, you have to obtain the MapperFacade from the MapperFactory and then use its map methods. There are two general options, <strong><em>map(objectA, B.class)</em></strong>, which will create a new instance of B.class and map the property values of objectA onto it, or <strong><em>map(objectA, objectB)</em></strong>, which copies properties from objectA onto objectB, being both of them not null.</p>
<p>Let&#8217;s see an example: </p>
<p></p><pre class="crayon-plain-tag">MapperFacade mapper = mapperFactory.getMapperFacade();
PersonDTO personDTO = new PersonDTO();
//Set values here
Person person = mapper.map(personDTO, Person.class);
//Alternatively:
//Person person = new Person();
//mapper.map(personDTO, person);</pre><p></p>
<p>The <strong>BoundMapperFacade</strong> is intended to be used with a pair of types to map and no further customization needed. It provides improved performance over use of the standard <strong>MapperFacade</strong> and it has the same usage plus a <strong><em>mapReverse</em></strong> method for mapping in the reverse direction.</p>
<p>See below an example:</p>
<p></p><pre class="crayon-plain-tag">BoundMapperFacade&lt;PersonDTO, Person&gt; boundMapper = mapperFactory.getMapperFacade(PersonDTO.class, Person.class);
PersonDTO personDTO = new PersonDTO();
//Set values here
Person person = boundMapper.map(personDTO);
//Alternatively:
//Person person = new Person();
//boundMapper.map(personDTO, person);
//Map in the reverse
PersonDTO personDTO = boundMapper.mapReverse(person);
//Alternatively with no null objects:
//boundMapper.mapReverse(person, personDTO); //curiously, it returns an A object instead of void</pre><p></p>
<p>If you’re primarily concerned with the mapping of a particular type to another, and your object graph has no cycles, use <strong>BoundMapperFacade</strong> because it has <u>better performance</u>, since you avoid the overhead of looking up an appropriate mapping strategy for the fields of the objects to be mapped, that happens when you call the map method.</p>
<h3>Performance</h3>
<p>The most expensive operations are instantiation and initialization of the MapperFactory, and the MapperFacade which is obtained from it.</p>
<p>Both of them are thread-safe objects, thus singletons or static access for them are a very recommended approach.</p>
<p>For instance, you can consider an static acces to the MapperFactory:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.domain.mappers;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

public class BaseMapper {
    final static MapperFactory MAPPER_FACTORY = new DefaultMapperFactory.Builder().build();
}</pre><p></p>
<p>And then use this class for registering class maps and access to the MapperFacade in a customize way:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.domain.mappers;

import com.malsolo.orika.test.domain.Customer;
import com.malsolo.orika.test.dto.CustomerDTO;
import ma.glasnost.orika.MapperFacade;

public enum CustomerMapper {
    
    INSTANCE;
    
    private final MapperFacade mapperFacade;
    
    private CustomerMapper() {
        BaseMapper.MAPPER_FACTORY.classMap(CustomerDTO.class, Customer.class)
                .byDefault()
                .register();
        mapperFacade = BaseMapper.MAPPER_FACTORY.getMapperFacade();
    }
    
    public Customer map(CustomerDTO customerDTO) {
        return this.mapperFacade.map(customerDTO, Customer.class);
    }
    
    public CustomerDTO map(Customer customer) {
        return this.mapperFacade.map(customer, CustomerDTO.class);
    }
}</pre><p></p>
<p>In this case I&#8217;m using two new classes: <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/domain/Customer.java" title="Customer at GitHub" target="_blank">Customer</a> and <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/dto/CustomerDTO.java" title="CustomerDTO at GitHub" target="_blank">CustomerDTO</a>.</p>
<p>Finally, just use this helper classes:</p>
<p></p><pre class="crayon-plain-tag">CustomerDTO customerDTO = new CustomerDTO();
//Setters at will
Customer customer = CustomerMapper.INSTANCE.map(customerDTO);</pre><p></p>
<h1>How it works and Customization</h1>
<p>The best way to understand how Orika works is to read the <a href="http://orika-mapper.github.io/orika-docs/faq.html" title="Orika FAQ" target="_blank">FAQ</a>, but the source code is very clear and easy to follow, just in case  you want to take a deeper look to the details.</p>
<p><em>&#8220;Orika uses reflection to investigate the metadata of the objects to be mapped and then generates byte-code at runtime which is used to map those classes [&#8230;]&#8221;</em></p>
<p><em>&#8220;Orika mapping is configured via Java code at runtime, via a fluent-style ClassMapBuilder API. An instance is obtained from a MapperFactory which is then used to describe the mapping from one type to another. Finally, the specified ClassMap is registered with the MapperFactory for later use in generating a byte-code mapper.&#8221;</em></p>
<p>To configure Orika, the author recommends to extend the ConfigurableMapper class, and I will use this approach for using Orika with Spring (see below)</p>
<p>If you want to configure the code generation, compilation and so on, see how to do this using the MapperFactory in the next topic.</p>
<h3>MapperFactory Configuration</h3>
<p>The core class <strong>MapperFactory</strong> is instantiated as you&#8217;ve seen above, by building the provided implementation: <strong>DefaultMapperFactory</strong>. It uses a set of Strategy and factory objects for resolving constructors, for compiling code (actually, they belong to its inner static class <strong>MapperFactoryBuilder</strong> that is extended by its other inner static class that you use to instantiate the MapperFactory: the <strong>Builder</strong>), for resolving properties, and specially for building class maps.</p>
<p>So you can customize all of them after calling <strong><em>Builder</em>()</strong> and before the <strong><em>build()</em></strong> method:</p>
<p></p><pre class="crayon-plain-tag">new DefaultMapperFactory.Builder()
.constructorResolverStrategy(new SimpleConstructorResolverStrategy()) //By default, you can extend it or implement your own ConstructorResolverStrategy
.compilerStrategy(new JavassistCompilerStrategy()) //By default, you can extend it, implement your own CompilerStrategy or use EclipseJdtCompilerStrategy
.propertyResolverStrategy(new IntrospectorPropertyResolver()) //By default, you can extend it or implement your own PropertyResolverStrategy
.classMapBuilderFactory(new ClassMapBuilder.Factory()) //by default. You can use //enabled by default or //enabled by default.Factory
.useAutoMapping(true) //enabled by default
.mapNulls(true) //enabled by default
.build();</pre><p></p>
<h3>Custom Mappers</h3>
<p>A <strong><em>Mapper&lt;A, B&gt;</em></strong> copies the properties from one object onto another and it&#8217;s used internally by Orika (MapperFacade, MapperGenerator and MapperFactory use it, but it isn&#8217;t really interesting for this post, actually)</p>
<p>If you want to take control of how properties of one object instance are copied to another object instance (not null), just extends the abstract class <strong><em>CustomMapper&lt;A,B&gt;</em></strong>.</p>
<p>Then, you can register your custom mapper in the <strong>MapperFactory</strong> via its method <strong><em>registerMapper(Mapper&lt;A, B&gt; mapper)</em></strong>.</p>
<p>It&#8217;s intended to be used when the mapping behavior configured via the ClassMapBuilder API doesn’t suit your purposes, but only to copy properties, that is, the destination object already exists. If you want to control instantiation, use a CustomConverter or ObjectFactory which both return an instance. See below.</p>
<p>If you need to map nested members of the given object, you can doing so by using the current <strong>MapperFacade</strong> that it&#8217;s accessible via a protected <strong><em>mapperFacade</em></strong> variable. </p>
<p>I&#8217;ve used converters in a Spring applications as components that can be scanned and used to configure the MapperFactory by extending ConfigurableMapper as I mentioned above and I&#8217;ll show below.</p>
<h3>Object Factories</h3>
<p>An <strong><em>ObjectFactory&lt;D&gt;</em></strong> instantiates objects. You can implement this interface and register your implementation in the MapperFactory via their method <strong><em>registerObjectFactory</em></strong> (there are a couple of them)</p>
<p>I&#8217;ve never used this option.</p>
<h3>Custom Converters</h3>
<p>A <strong><em>Converter&lt;S, D&gt;</em></strong> combines both ObjectFactory and Mapper together, returning a new instance of the destination type with all properties copied from the source instance.</p>
<p>When you want to take complete control over the instantiation and mapping, just extend <strong><em>CustomConverter&lt;S, D&gt;</em></strong> to create the new instance and to provide it the properties from the source object.</p>
<p>Then, you can register your custom converter in the MapperFactory by obtaining its <strong>ConverterFactory</strong> via the <strong><em>getConverterFactory()</em></strong> method and then using one of its <strong><em>registerConverter()</em></strong> methods.</p>
<p>I&#8217;ve found this option useful when you want to create some hard conversion between classes that has the same meaning in your code but are not really related in terms of Java. Well, it&#8217;s a conversion, let&#8217;s say, from a date represented in a String and a date that has to be a Calendar. You have to use some formatter for doing so.</p>
<p>It&#8217;s also very easy to configure converters as Spring components if you need so.</p>
<h1>Using Orika with Spring</h1>
<p>Since the Orika core classes <strong>MapperFactory</strong> and the <strong>MapperFacade</strong> obtained from it are very expensive to instantiate and initialize, but at the same time are thread-safe, they should be shared as singletons. That is, they are good candidates for being Spring beans with singleton scope.</p>
<p>Let&#8217;s start with using spring-framework in a maven project,just add the next dependency to the pom.xml file:</p>
<p></p><pre class="crayon-plain-tag">&lt;dependency&gt;
			&lt;groupId&gt;org.springframework&lt;/groupId&gt;
			&lt;artifactId&gt;spring-context&lt;/artifactId&gt;
			&lt;version&gt;4.1.1.RELEASE&lt;/version&gt;&lt;!-- or latest version --&gt;
		&lt;/dependency&gt;</pre><p></p>
<h3>The Spring application</h3>
<p>Let&#8217;s create a couple of beans to obtain a Person and a PersonDTO, let&#8217;s call them service and repository respectively:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.domain.Person;

public interface PersonService {
    
    public Person obtainPerson();
    
}</pre><p></p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.dto.PersonDTO;

public interface PersonRepository {
    
    public PersonDTO obtainPerson();

}</pre><p></p>
<p>And their implementations, the one for the service will use the repository interface, and the one for the repository will be a simple in-memory implementation.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.google.common.collect.ImmutableList;
import com.malsolo.orika.test.dto.PersonDTO;
import java.util.Random;
import org.springframework.stereotype.Repository;

@Repository
public class PersonRepositoryImpl implements PersonRepository {
    
    Random random = new Random();

    @Override
    public PersonDTO findPerson() {
        return this.createPersonDTO(random.nextLong());
    }

    private PersonDTO createPersonDTO(long l) {
        PersonDTO dto = new PersonDTO();
        dto.setId(l);
        //More setters here
        return dto;
    }
}</pre><p></p>
<p>Note that the service will need to convert from the DTO to the domain object, so let&#8217;s inject a mapper.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.domain.Person;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonServiceImpl implements PersonService {
    
    @Autowired
    private PersonRepository personRepository;
    
    private MapperFacade mapper;

    @Autowired
    public void setMapperFactory(MapperFactory mapperFactory) {
        this.mapper = mapperFactory.getMapperFacade();
    }
    
    @Override
    public Person obtainPerson() {
        return mapper.map(this.personRepository.findPerson(), Person.class);
    }

}</pre><p></p>
<p>As you can see, I used setter injection (via autowiring) to provide a MapperFactory in order to obtain from it a MapperFacade. I&#8217;m using the suggestion of having the MapperFactory as singleton, that it&#8217;s easy to achieve with Spring.</p>
<p>Since MapperFactory has a particular way to be instantiated, the best option is to create a factory for exposing it, a FactoryBean:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.stereotype.Component;

@Component
public class MapperFactoryFactory implements FactoryBean&lt;MapperFactory&gt; {

    @Override
    public MapperFactory getObject() throws Exception {
        return new DefaultMapperFactory.Builder().build();
    }

    @Override
    public Class&lt;?&gt; getObjectType() {
        return MapperFactory.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

}</pre><p></p>
<p>This approach has been selected just in case I want to use a BoundMapperFacade, but it&#8217;s possible to use a MapperFacade directly by creating a <a href="http://github" title="title" target="_blank">MapperFacadeFactory</a>.</p>
<p>Now, let&#8217;s configure the Spring application</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class OrikaSpringTest {
    
    public static void main(String... args) {
        ApplicationContext context = 
          new AnnotationConfigApplicationContext(OrikaSpringTest.class);
        PersonService personService = context.getBean(PersonService.class);
        Person person = personService.obtainPerson();
        System.out.printf(&quot;%s\n&quot;, person.toString());
    }

}</pre><p></p>
<p>This is enough for the project to run:</p>
<p></p><pre class="crayon-plain-tag">Person{id=0, name=Name 0, surnames=null, address=null}</pre><p></p>
<p>But <strong><u>pay attention</u></strong>, the mapper didn&#8217;t work, because there are differences between the two classes (tow attributes with different names, and the same concept, address, with different types)</p>
<h3>Plugging in Orika Mappers and Converters with Spring</h3>
<p>Orika provides custom converters and mappers, so the only thing we need is to configure them as spring beans in the application context. Let&#8217;s see how to do this.</p>
<p>First, we need a custom mapper. We annotate it as component to be discovered (via component scanning) by Spring.</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import com.malsolo.orika.test.domain.Address;
import com.malsolo.orika.test.domain.Person;
import com.malsolo.orika.test.dto.PersonDTO;
import ma.glasnost.orika.CustomMapper;
import ma.glasnost.orika.MappingContext;
import org.springframework.stereotype.Component;

@Component
public class PersonDtoToPersonMapper extends CustomMapper&lt;PersonDTO, Person&gt; {

    @Override
    public void mapAtoB(PersonDTO a, Person b, MappingContext context) {
        b.setId(a.getId());
        b.setName(a.getName());
        b.setSurnames(a.getLastNames());
        //I could use the protected mapperFacade if I need to map a particular field
        //this.mapperFacade.map(sourceObject, destinationClass);
        Address address = new Address();
        address.setStreet(a.getStreetAddress());
        address.setCity(a.getCity());
        address.setZipCode(a.getPostalCode());
        b.setAddress(address);
    }

    @Override
    public void mapBtoA(Person b, PersonDTO a, MappingContext context) {
        a.setId(b.getId());
        a.setName(b.getName());
        a.setLastNames(b.getSurnames());
        Address address = b.getAddress();
        if (address != null) {
            a.setStreetAddress(address.getStreet());
            a.setCity(address.getCity());
            a.setPostalCode(address.getZipCode());
        }
    }

}</pre><p></p>
<p>Finally, we have to plug in mappers and converters that belongs to the Spring application context, into the MapperFactory. If we extend <strong>ConfigurableMapper</strong> we will have a MapperFactory created for us, and later on, the chance to access the application context itself to look up for the custom mappers and converters that are Spring components to register them in the MapperFactory.</p>
<p>Let&#8217;s show the code:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import java.util.Map;
import ma.glasnost.orika.Converter;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class SpringConfigurableMapper extends ConfigurableMapper {

    private ApplicationContext applicationContext;

    private MapperFactory mapperFactory;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        addSpringMappers();
        addSpringConverter();
    }

    @Override
    protected void configure(MapperFactory factory) {
        super.configure(factory);
        this.mapperFactory = factory;
    }

    private void addSpringMappers() {
        @SuppressWarnings(&quot;rawtypes&quot;)
        final Map&lt;String, Mapper&gt; mappers = applicationContext
                .getBeansOfType(Mapper.class);
        for (final Mapper&lt;?, ?&gt; mapper : mappers.values()) {
            addMapper(mapper);
        }
    }

    private void addMapper(Mapper&lt;?, ?&gt; mapper) {
        this.mapperFactory.registerMapper(mapper);
    }

    private void addSpringConverter() {
        @SuppressWarnings(&quot;rawtypes&quot;)
		final Map&lt;String, Converter&gt; converters = applicationContext
                .getBeansOfType(Converter.class);
        for (final Converter&lt;?, ?&gt; converter : converters.values()) {
            addConverter(converter);
        }
    }

    private void addConverter(Converter&lt;?, ?&gt; converter) {
        this.mapperFactory.getConverterFactory().registerConverter(converter);
    }

}</pre><p></p>
<p>Some important things to note here:</p>
<ul>
<li>Our class SpringConfigurableMapper is a @Component</li>
<p>When Spring instantiates it, it will call its constructor that is inherited from <strong>ConfigurableMapper</strong> and it calls an init method that creates a MapperFactory and allows you to configure via the overriden method. </p>
<p>So, the first method called is <strong><em>configure(MapperFactory)</em></strong>.</p>
<p>Furthermore, don&#8217;t create your own MapperFactory as I did above, because it won&#8217;t be the one you&#8217;ll use to register the mappers and converters, on the contrary, this class will create a new MapperFactory.</p>
<li>Our class SpringConfigurableMapper has the ApplicationContext @Autowired</li>
<p>It&#8217;s the same as if you implement ApplicationContextAware, but I&#8217;d rather this approach.</p>
<p>Besides, it implies that the method will be called after all the beans have been created. Since you already have a MapperFactory, you can then search for custom components and converters that are spring beans and register them in the MapperFactory.</p>
<li>Our class extends ConfigurableMapper that implements MapperFacade</li>
<p>So, you have to slightly change the PersonServiceImpl and it&#8217;s better to not have a MapperFacadeFactory or you will have an autowiring exception because there would be two beans of the MapperFacade class:</p>
<p></p><pre class="crayon-plain-tag">package com.malsolo.orika.test.spring;

import ma.glasnost.orika.MapperFacade;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.malsolo.orika.test.domain.Person;

@Service
public class PersonServiceImpl implements PersonService {
    
    @Autowired
    private PersonRepository personRepository;
    
    @Autowired
    private MapperFacade mapper;

    @Override
    public Person obtainPerson() {
        return mapper.map(this.personRepository.findPerson(), Person.class);
    }

}</pre><p></p>
<p>Now, if you run the Orika with Spring main class, <a href="https://github.com/jbbarquero/orika-test/blob/master/src/main/java/com/malsolo/orika/test/spring/OrikaSpringTest.java" title="Orika Spring test at GitHub" target="_blank">OrikaSpringTest</a>, everything will run as expected:</p>
<p></p><pre class="crayon-plain-tag">Person{id=85, name=Name 85, surnames=[S., Surname 85], address=Address{street=My street 85, city=City 85, zipCode=code 85}}</pre><p></p>
<h1>Resources</h1>
<ul>
<li><a href="https://github.com/jbbarquero/orika-test" title="Source code at GitHub" target="_blank">Source code</a> for this post</li>
<li><a href="http://orika-mapper.github.io/orika-docs/" title="Orika user guide" target="_blank">Orika User Guide</a></li>
<li><a href="http://kenblair.net/orika-spring-easy-bean-mapping/" title="Orika and Spring Framework = easy bean mapping" target="_blank">Orika and Spring Framework = easy bean mapping</a> by Ken Blair</li>
<li><a href="http://projects.spring.io/spring-framework/#quick-start" title="Spring Framework Quick Start" target="_blank">Spring Framework Quick Start</a></li>
<li><a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#extensible-xml-meat" title="Spring Framework Reference Documentation: 35.7. Meatier examples" target="_blank">Spring Framework Reference Documentation (Meatier examples)</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://malsolo.com/blog4java/?feed=rss2&#038;p=465</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
