Spring - applicationContext.xml无法打开,因为它不存在

Tim*_*Tim 34 junit spring-mvc

我有一个Spring MVC应用程序和JUnit测试与文件applicationContext.xml相结合的问题.

在我的JUnit测试类中,我写道:

final ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
service = (TestServiceImpl) context.getBean("testServiceImpl");
Run Code Online (Sandbox Code Playgroud)

我得到的错误是找不到aplicationContect.xml:

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
Run Code Online (Sandbox Code Playgroud)

但它退出WEB-INF文件夹.在这里,您可以使用applicationContext.xml文件查看项目树:http: //img28.imageshack.us/img28/2576/treexp.png

那么,这里有什么问题?为什么JUnit测试不存在该文件?

提前谢谢你和最诚挚的问候.

bia*_*bit 38

您应该将Spring文件保存在另一个文件夹中,标记为"source"(就像"src"或"resources").

WEB-INF不是源文件夹,因此它不会包含在类路径中(即JUnit不会在那里查找任何内容).


dur*_*ell 9

如果使用maven,请resources在主目录中创建一个目录,然后将applicationContext.xml其复制到其中.

从你的java代码调用:

ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我使用 maven 并将 applicationContext.xml 放入资源中立即解决了我的问题! (3认同)

Nat*_*hes 8

ClassPathXmlApplicationContext不会找到applicationContext.xml你的WEB-INF文件夹,它不是在类路径中.您可以src/test/resources在运行测试时将应用程序上下文复制到类路径中(可以将其置于其下并让Maven将其复制).


小智 8

我得到了同样的错误.我解决了它移动文件applicationContext.xml的问题

文件夹的子文件src夹.例如:

context = new ClassPathXmlApplicationContext("/com/ejemplo/dao/applicationContext.xml");
Run Code Online (Sandbox Code Playgroud)


Bil*_*low 5

我也发现了这个问题。解决此问题的方法是将该文件复制/粘贴到各处并运行,一次只运行一个文件。最终,它成功编译并运行,然后删除了不必要的内容。我所处的正确位置是: 在此处输入图片说明

这在/ src /路径下(我正在使用Intellij Idea作为IDE)。其他Java源文件位于/ src / com / package /路径下

希望对您有所帮助。