How to use Dozer with Spring Boot?

拈花ヽ惹草 提交于 2019-11-30 12:06:49

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;
  }

  ...
}

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.

bhdrkn

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);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!