简体   繁体   English

如何在Spring中从classpath注入资源?

[英]How to inject a Resource from classpath in Spring?

I want to inject a file from src/main/resources like this: 我想从src/main/resources注入一个文件,如下所示:

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

When I run this from eclipse it works fine. 当我从eclipse运行它时它工作正常。 But from a standalone folder, the file is not found: 但是从独立文件夹中找不到该文件:

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]

How can I tell spring that the file to be injected is actually in the root of the jar, not an absolute path? 我怎么能告诉spring要注入的文件实际上是在jar的根目录中,而不是绝对路径?

Same result if I try to load it programmatically. 如果我尝试以编程方式加载它,结果相同。

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

You said this works in eclipse: 你说这在eclipse中起作用:

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

Now try this in eclipse (notice the * ), if it works, standalone should be ok: 现在在eclipse中尝试这个(注意* ),如果它工作,独立应该没问题:

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

When deploying outside eclipse, make sure myfile.txt is on the classpath; 在eclipse之外部署时,请确保myfile.txt在classpath上; the best location is in the root directory where Java class file packages are located ( com , org ) 最佳位置位于Java类文件包所在的根目录中( comorg

It turned out the injection itself did work, BUT I accessed the file using res.getFile() which threw the NPE. 事实证明注入本身确实有效,但我使用res.getFile()来访问该文件,该文件抛出了NPE。

When just retrieving the URL and fetching the file explicit with File file = ResourceUtils.getFile(res.getURL().getFile()); 当只检索URL并使用File file = ResourceUtils.getFile(res.getURL().getFile());显式获取文件时File file = ResourceUtils.getFile(res.getURL().getFile()); it worked as expected. 它按预期工作。

Though I'm not sure wether this is a bug or works as expected. 虽然我不确定这是一个错误还是按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM