问题
In my Spring application, I have a simple properties file located in folder WEB-INF\classes
so that it, the DispatcherServlet
and various other config files are in the classpath
.
The props file is defined in the DispatcherServlet
as:
<bean id="propertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>/WEB-INF/classes/library.properties</value>
</property>
</bean>
The propertiesFactory
bean is injected into a controller:
@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
:
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?
回答1:
Everything in WEB-INF/classes
is added to the root of the classpath. As such, you need to refer to your resource simply as
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.
来源:https://stackoverflow.com/questions/24598140/java-io-filenotfoundexception-class-path-resource-web-inf-classes-library-prop