How to use Dozer with Spring Boot?

Just in case someone wants to avoid xml dozer file. You can use a builder directly in java. For me it's the way to go in a annotation Spring context.

See more information at mapping api dozer

    @Bean
public DozerBeanMapper mapper() throws Exception {
    DozerBeanMapper mapper = new DozerBeanMapper();
    mapper.addMapping(objectMappingBuilder);
    return mapper;
}

BeanMappingBuilder objectMappingBuilder = new BeanMappingBuilder() {
    @Override
    protected void configure() {
        mapping(Bean1.class, Bean2.class)
                .fields("id", "id").fields("name", "name");
    }
};

In my case it was more efficient (At least the first time). Didn't do any benchmark or anything.


If you are using DozerBeanMapperFactoryBean instead of DozerBeanMapper you may use something like this.

@Configuration
public class MappingConfiguration {

    @Bean
    public DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean(@Value("classpath*:mappings/*mappings.xml") Resource[] resources) throws Exception {
        final DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean = new DozerBeanMapperFactoryBean();
        // Other configurations
        dozerBeanMapperFactoryBean.setMappingFiles(resources);
        return dozerBeanMapperFactoryBean;
    }
}

This way you can import your mappings automatically. Than simple inject your Mapper and use.

@Autowired
private Mapper mapper;

Update with Dozer 5.5.1

In dozer 5.5.1, DozerBeanMapperFactoryBean is removed. So if you want to go with an updated version you need do something like below,

@Bean
public Mapper mapper(@Value(value = "classpath*:mappings/*mappings.xml") Resource[] resourceArray) throws IOException {
    List<String> mappingFileUrlList = new ArrayList<>();
    for (Resource resource : resourceArray) {
        mappingFileUrlList.add(String.valueOf(resource.getURL()));
    }
    DozerBeanMapper dozerBeanMapper = new DozerBeanMapper();
    dozerBeanMapper.setMappingFiles(mappingFileUrlList);
    return dozerBeanMapper;
}

Now inject mapper as told above

@Autowired
private Mapper mapper;

And use like below example,

mapper.map(source_object, destination.class);

eg. mapper.map(admin, UserDTO.class);


I think something like this should work:

@Configuration
public class YourConfiguration {

  @Bean(name = "org.dozer.Mapper")
  public DozerBeanMapper dozerBean() {
    List<String> mappingFiles = Arrays.asList(
      "dozer-global-configuration.xml", 
      "dozer-bean-mappings.xml",
      "more-dozer-bean-mappings.xml"
    );

    DozerBeanMapper dozerBean = new DozerBeanMapper();
    dozerBean.setMappingFiles(mappingFiles);
    return dozerBean;
  }

  ...
}