Spring:向bean注入resources文件夹中文件的路径



我定义了以下springbean,其中一个属性有一个文件路径:

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

但这不起作用,抛出未找到文件的错误。

将路径插入到资源文件夹中的文件位置的正确方法是什么?

根据我的理解,你想加载一个位于资源文件夹中的文件,并且你想读取它。

这种手动方式你可以使用:

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

您可以从类路径读取文件。

最新更新