Search code examples
javaspringautowiredproperties-file

Autowire List<List<String>> out of properties file with unknown keys length


is there a way to autowire a list containing Strings inside another list read from a properties-file? The difficulty I found is that the property-values need to be split to become a String list (or Array) and shall then be autowired to. My properties-file looks something like this:

jobFolders1=C:/Temp/originFolder, C:/Temp/trafoIn, C:/Temp/trafoOut, C:/Temp/destinationFolder
jobFolders2=C:/Temp/originFolder2, C:/Temp/trafoIn2, C:/Temp/trafoOut2, C:/Temp/destinationFolder2

Now I want my users to be able to add lines to that file, whenever there are new jobs. So I never know the names of the keys, nor the amount of lines. Is there some way to autowire the file-entries to a List which itself contains a List containing the 4 Strings (split by ",")? Probably this entire approach is not the best. If so, please feel free to tell me so.


Solution

  • Alright, following is a quite "springy" solution, although I think one could solve this more elegant (without writing custom code at all):

    Write a PropertyMapper:

    @Component("PropertyMapper")
    public class PropertyMapper {
    
    @Autowired
    ApplicationContext context;
    @Autowired
    List<List<String>> split;
    
    public List<List<String>> splitValues(final String beanname) {
    ((Properties) this.context.getBean(beanname)).values().forEach(v -> {
    final List<String> paths = Arrays.asList(((String) v).split(","));
    paths.forEach(p -> paths.set(paths.indexOf(p), p.trim()));
    this.split.add(paths);
    });
    return this.split;
    }
    

    Load properties in context.xml like this:

    <util:properties id="testProps" location="classpath:test.properties"/>
    

    And then wire the values to the field, using Spring EL 'tweaking' the original values by calling splitValues method on them:

    @Value("#{PropertyMapper.splitValues('testProps')}")
    private List<List<String>> allPaths;