在我的Spring应用程序中,我在文件夹WEB-INFclasses
中有一个简单的属性文件,因此它,DispatcherServlet
和其他各种配置文件都在classpath
中。
props文件在DispatcherServlet
中定义为:
<bean id="propertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>/WEB-INF/classes/library.properties</value>
</property>
</bean>
propertiesFactory
bean被注入到控制器中:
@Autowired
private Properties propertiesFactory;
并且在一个控制器的方法中使用,如:
if (adminPassword.equals(propertiesFactory.getProperty("adminPassword"))) {
这一切都很完美,除了下面的一个测试程序,它有一行:
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("library-servlet.xml");
抛出BeanCreationException
:
Injection of autowired dependencies failed
因为:java.io.FileNotFoundException: class path resource [WEB-INF/classes/library.properties] cannot be opened because it does not exist
但是,如果整个应用程序都可以看到props文件,为什么不能只看到这个程序呢?
WEB-INF/classes
中的所有内容都被添加到类路径的根目录中。因此,您需要将您的资源简单地引用为
library.properties
或者更好的
classpath:library.properties
<property name="location">
<value>classpath:library.properties</value>
</property>
你可能会发现运行
很有用System.out.println(System.getProperty("java.class.path"));