Spring - java.io.FileNotFoundException:无法打开类路径资源,因为它不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39964902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:35:48  来源:igfitidea点击:

Spring - java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

javaspringspring-boot

提问by Punter Vicky

I am developing a Spring Boot application which has a dependency added. This dependency has a spring.xml file. I am scanning this xml file and creating beans as well. One of the beans is looking for hibernate.properties in classpath. I have added this property file under resources folder of my application. However I still see the exception listed below. Please can you let me know what I am missing?

我正在开发一个添加了依赖项的 Spring Boot 应用程序。这个依赖有一个 spring.xml 文件。我正在扫描这个 xml 文件并创建 bean。其中一个 bean 正在类路径中寻找 hibernate.properties。我已经在我的应用程序的资源文件夹下添加了这个属性文件。但是,我仍然看到下面列出的异常。请你能告诉我我错过了什么吗?

 <util:properties id="HibernateProperties" location="classpath:hibernate.properties"/>

java.io.FileNotFoundException: class path resource [hibernate.properties] cannot be opened because it does not exist

java.io.FileNotFoundException: 类路径资源 [hibernate.properties] 无法打开,因为它不存在

采纳答案by kuhajeyan

Here some doc from spring

这里有一些春天的文档

Ant-style patterns with classpath: resources are not guaranteed to find matching resources if the root package to search is available in multiple class path locations. This is because a resource such as

com/mycompany/package1/service-context.xml may be in only one location, but when a path such as

classpath:com/mycompany/**/service-context.xml

带有类路径的 Ant 样式模式:如果要搜索的根包在多个类路径位置可用,则不能保证资源找到匹配的资源。这是因为像这样的资源

com/mycompany/package1/service-context.xml 可能只在一个位置,但是当路径如

类路径:com/mycompany/**/service-context.xml

so,

所以,

<util:properties id="HibernateProperties" location="classpath*:hibernate.properties"/> 

may give you better chance.

可能会给你更好的机会。

but,

但,

Please note that classpath*: when combined with Ant-style patterns will only work reliably with at least one root directory before the pattern starts, unless the actual target files reside in the file system. This means that a pattern like classpath*:*.xml will not retrieve files from the root of jar files but rather only from the root of expanded directories. This originates from a limitation in the JDK's ClassLoader.getResources() method which only returns file system locations for a passed-in empty string (indicating potential roots to search).

请注意,classpath*: 当与 Ant 风格的模式结合使用时,在模式启动之前,它只能在至少一个根目录下可靠地工作,除非实际的目标文件驻留在文件系统中。这意味着像 classpath*:*.xml 这样的模式不会从 jar 文件的根目录检索文件,而只会从扩展目录的根目录检索文件。这源于 JDK 的 ClassLoader.getResources() 方法中的限制,该方法仅返回传入空字符串的文件系统位置(指示要搜索的潜在根)。