春季:注入带有指向资源文件夹中文件路径的bean

时间:2020-09-26 05:05:04

标签: spring

我定义了以下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>

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

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

1 个答案:

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

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