[英]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: 但是,我有成百上千个.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>
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. 我希望能调用listFiles
通过所有与循环.lookup
文件,但是这似乎并没有工作,我得到一个NullPointerException异常,因为传递的路径没有被解析为一个目录。
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 您需要使用PathMatchingResourcePatternResolver
,请参阅文档: 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 ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.