简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM