gpt4 book ai didi

java - 如何在 Spring 中从类路径注入(inject)资源?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:29 26 4
gpt4 key购买 nike

我想像这样从 src/main/resources 注入(inject)一个文件:

@Value("classpath:myfile.txt")
private Resource res;

当我从 eclipse 运行它时,它工作正常。但是在独立文件夹中,找不到该文件:

Caused by: java.io.FileNotFoundException: class path resource [myfile.txt] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/myapp/myapp-1.0.0.jar!/myfile.txt
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:212) ~[spring-core-4.1.4.RELEASE.jar:4.1.4.RELEASE]

如何告诉spring要注入(inject)的文件实际上是在jar的根目录下,而不是绝对路径?

如果我尝试以编程方式加载它,结果相同。

res = new ClassPathResource("myfile.txt");

最佳答案

事实证明注入(inject)本身确实有效,但我使用 res.getFile() 访问了该文件,这引发了 NPE。

当仅检索 URL 并使用 File file = ResourceUtils.getFile(res.getURL().getFile()); 显式获取文件时,它按预期工作。

虽然我不确定这是错误还是按预期工作。

关于java - 如何在 Spring 中从类路径注入(inject)资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28563576/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com