我定义了以下spring bean,其属性之一具有文件路径:
<bean class="com.test.MyBean" name="myBean">
<property name="artifact" value="path/to/MyFile.txt"></property>
</bean>
这很好。但是我想把文件放在资源文件夹中。所以我在上面修改为:
<property name="artifact" value="classpath:MyFile.txt"></property>
但这不起作用,抛出未找到文件的错误。
将路径注入资源文件夹中文件位置的正确方法是什么?
答案 0 :(得分:0)
根据我的理解,您想加载资源文件夹中的文件并要读取它。
您可以使用以下手动方式:
public Resource loadFile() {
return new ClassPathResource("MyFile.txt"); // Either you can use the value which set on bean value
}
或
@Autowired private ResourceLoader resourceLoader;
public Resource loadFile() {
return resourceLoader.getResource("classpath:MyFile.txt"); // Here the value would come from xml which you set in bean definition.
}
或
public File loadFile() throws FileNotFoundException {
return ResourceUtils.getFile("classpath:MyFile.txt");// Here the value would come from xml which you set in bean definition.
}
您可以或者可以从类路径中读取文件。