如何在Spring Boot中使用Dozer?

时间:2015-02-06 15:44:12

标签: java spring annotations dto dozer

我正在开发一个Spring Boot项目。我只有注释配置。我想包括推土机将实体转换为DTO,将DTO转换为实体。我在dozer网站上看到,他们解释说我必须在spring xml配置文件中添加以下配置。由于我没有xml文件而是注释配置Java类,我不知道如何将其转换为Java Configuration类。

<bean id="org.dozer.Mapper" class="org.dozer.DozerBeanMapper">
  <property name="mappingFiles">
    <list>
      <value>dozer-global-configuration.xml</value>
      <value>dozer-bean-mappings.xml</value>
      <value>more-dozer-bean-mappings.xml</value>
    </list>
  </property>
</bean>

如果有人能给我一个例子,它会非常有用。感谢

3 个答案:

答案 0 :(得分:17)

我认为这样的事情应该有效:

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

  ...
}

答案 1 :(得分:8)

如果您使用DozerBeanMapperFactoryBean代替DozerBeanMapper,则可以使用此类内容。

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

这样您就可以自动导入映射。而不是简单地注入你的Mapper并使用。

@Autowired
private Mapper mapper;
  

使用Dozer 5.5.1进行更新

在dozer 5.5.1中,删除了DozerBeanMapperFactoryBean。因此,如果您想使用更新版本,则需要执行以下操作,

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

现在按照上面的说法注入mapper

@Autowired
private Mapper mapper;

并使用如下例子,

mapper.map(source_object, destination.class);

例如。     mapper.map(admin,UserDTO.class);

答案 2 :(得分:8)

以防万一有人想要避免使用xml推文文件。您可以直接在java中使用构建器。对我来说,它是注释Spring上下文的方式。

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

就我而言,效率更高(至少第一次)。没有做任何基准或任何事情。