Koray Tugay
Koray Tugay

Reputation: 23770

Spring Framework - How to inject a Directory as a Resource?

This is the current configuration I have which works ok:

<bean id="foo"
      class="foo.Foo">
    <constructor-arg>
        <list value-type="org.springframework.core.io.Resource">
            <value>classpath:bar/01.lookup</value>
            <value>classpath:bar/02.lookup</value>
            <value>classpath:bar/03.lookup</value>
        </list>
    </constructor-arg>
</bean>

However, I have hundreds of these .lookup files, so I created a constructor in class Foo which expects a Path to a folder, and my naive approach was:

<bean id="foo"
      class="foo.Foo">
    <constructor-arg>
        <bean class="org.springframework.core.io.FileSystemResource">
            <constructor-arg>
                <value>classpath:bar</value>
            </constructor-arg>
        </bean>
    </constructor-arg>
</bean>  

and I was hoping to call listFiles and loop through all .lookup files, but this does not seem to work and I am getting a NullPointerException since the passed path is not resolved as a directory.

Upvotes: 1

Views: 884

Answers (1)

Pavel Molchanov
Pavel Molchanov

Reputation: 2409

You need to use PathMatchingResourcePatternResolver, see the documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html

Code example:

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath*:bar/*.lookup") ;
for (Resource resource: resources){
    ... process resource here ...
}

Upvotes: 5

Related Questions