Search code examples
javafiledirectorydozer

Load all dozer xml files in a directory


In Dozer we can inject XML custom mapping files to Dozer via setMappingFiles function.

List myMappingFiles = new ArrayList();
myMappingFiles.add("dozerBeanMapping.xml");
myMappingFiles.add("someOtherDozerBeanMappings.xml"); DozerBeanMapper
mapper = new DozerBeanMapper();
mapper.setMappingFiles(myMappingFiles);

but i have 100 XML files in a directory in resources Classpath folder. what is best solution for inject them into Dozer?

I try this in spring5:

  @Value("classpath*:dozer/*.xml")
  private Resource[] resources;

  @Bean(name = "org.dozer.Mapper")
  public DozerBeanMapper dozerBean() {
    DozerBeanMapper dozerBean = new DozerBeanMapper();
    dozerBean.setMappingFiles(resources); //this is wrong
    return dozerBean;
  }

Solution

  • I don't identify in DozerBeanMapper a method that provides such a way.

    As workaround : map the resources to a List<String> and you could so use DozerBeanMapper.setMappingFiles(List<String> mappingFileUrls).
    Note that you can inject List<Resources> instead of Resource[] that is more handy.

    @Value("classpath*:dozer/*.xml")
    private List<Resources> resources;
    
    @Bean(name = "org.dozer.Mapper")
    public DozerBeanMapper dozerBean() {
       List<String> xmlString = 
               resources.stream()
                        .map(t -> {
                                    try {
                                          return t.getFile().toURI().toURL().toString();   
                                        }
                                        catch (IOException e) {
                                          throw new RuntimeException(e);
                                        }
                            })  
                         .collect(Collectors.toList());
    
        DozerBeanMapper dozerBean = new DozerBeanMapper();
        dozerBean.setMappingFiles(xmlString );
        return dozerBean;
    }