2016-11-18 28 views
0

我无法让Spring从我的类路径中读取applicationContext.xml文件。如何在类路径中指定资源

appContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); 

appContext = new ClassPathXmlApplicationContext("applicationContext.xml"); 

原因下面的错误。

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource 
[applicationContext.xml] cannot be opened because it does not exist 
at 
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) 
at 
org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) 

以下代码正确列出了我的classpath上的所有jar文件,包括带有applicationContext文件的jar文件。

ClassLoader cl = ClassLoader.getSystemClassLoader(); 
URL[] urls = ((URLClassLoader)cl).getURLs(); 
for(URL url: urls){System.out.println(url.getFile());} 

其中一个罐子都有一个包含我的“的applicationContext.xml”文件资源文件夹。我用7-Zip打开了jar文件,确保它在那里。

我添加了一些代码,试图查看列出我的jar文件的类加载器是否可以找到它。

URL appContextURL=cl.getResource("applicationContext.xml"); 
if(appContextLocation==null){ 
    logger.info("context not found in classpath"); 
}else{ 
    logger.info("Application context found at " + appContextLocation); 
} 

这也找不到它。

我该怎么做才能确保找到applicationContext.xml?

+0

你把你的applicationContext.xml放在哪里? – kuhajeyan

+0

您正在使用哪种IDE? –

+1

如果它有一个'resources'文件夹,那么你的路径应该是'/ resources/applicationContext.xml',你现在将会从classpath的根目录下载它。 –

回答

0

答案是解决相对路径以包含文件夹M. Deinum建议。

appContext = new ClassPathXmlApplicationContext("classpath:resources/applicationContext.xml"); 

,并在调试

URL appContextURL=cl.getResource("applicationContext.xml"); 

这种需求并没有出现在任何的,我发现上线使我推测,这种结构是在Eclipse和Maven使用默认值的结果的例子同时建立罐子。

感谢大家提出的很好的问题和建议。