java.io.FileNotFoundException: 类路径资源 [WEB-INF/classes/library.properties] 无法打开,因为它不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24598140/
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-14 13:20:25  来源:igfitidea点击:

java.io.FileNotFoundException: class path resource [WEB-INF/classes/library.properties] cannot be opened because it does not exist

javaspringdependency-injectionproperties-file

提问by Mr Morgan

In my Spring application, I have a simple properties file located in folder WEB-INF\classesso that it, the DispatcherServletand various other config files are in the classpath.

在我的 Spring 应用程序中,我在文件夹中有一个简单的属性文件,WEB-INF\classes因此它、DispatcherServlet以及其他各种配置文件都在classpath.

The props file is defined in the DispatcherServletas:

props 文件定义DispatcherServlet为:

<bean id="propertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location">            
           <value>/WEB-INF/classes/library.properties</value>
        </property>
    </bean>

The propertiesFactorybean is injected into a controller:

propertiesFactorybean被注入到一个控制器:

@Autowired 
private Properties propertiesFactory;

And used in a one of the controller's methods as:

并在控制器的方法之一中用作:

if (adminPassword.equals(propertiesFactory.getProperty("adminPassword"))) {           

This all works perfectly, except for a test program as follows which has line:

这一切都完美无缺,除了如下的测试程序,它有一行:

ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("library-servlet.xml");

Which throws a BeanCreationException:

其中抛出一个BeanCreationException

Injection of autowired dependencies failed

Because of:

因为:

java.io.FileNotFoundException: class path resource [WEB-INF/classes/library.properties] cannot be opened because it does not exist

But if the whole application can see the props file, why not this one program?

但是如果整个应用程序都可以看到 props 文件,为什么不能看到这个程序呢?

采纳答案by Sotirios Delimanolis

Everything in WEB-INF/classesis added to the root of the classpath. As such, you need to refer to your resource simply as

中的所有内容都WEB-INF/classes添加到类路径的根目录中。因此,您需要将您的资源简单地称为

library.properties

or better yet

或者更好

classpath:library.properties

in

<property name="location">            
    <value>classpath:library.properties</value>
</property>

You may find it useful to run

你可能会发现运行它很有用

System.out.println(System.getProperty("java.class.path"));

and see what was used as classpath entries.

并查看用作类路径条目的内容。