Spring Framework - 如何将目录注入资源?

时间:2018-06-15 18:00:29

标签: java spring io path

这是我现有的配置正常:

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

但是,我有数百个这样的.lookup文件,所以我在类Foo中创建了一个构造函数,它需要一个文件夹的路径,我的天真方法是:

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

我希望调用listFiles并遍历所有.lookup文件,但这似乎不起作用,我得到一个NullPointerException,因为传递的路径没有被解析为目录。 / p>

1 个答案:

答案 0 :(得分:2)

您需要使用PathMatchingResourcePatternResolver,请参阅文档: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/support/PathMatchingResourcePatternResolver.html

代码示例:

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