ClassPathXmlApplicationContext错误,Spring框架

时间:2016-06-02 09:07:36

标签: java mysql spring hibernate maven

我遇到了Spring框架的问题,导致服务器和数据库之间的通信不起作用。

我创建的项目是一个Spring项目,然后重构为Maven。

在代码中的这一行: ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("projectName/spring.xml");

我收到此错误: Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [projectName/spring.xml]; nested exception is java.io.FileNotFoundException: class path resource [projectName/spring.xml] cannot be opened because it does not exist

但确实存在。我已经尝试过解决此问题的方法,例如编写ClassPathXmlApplicationContext("spring.xml")。但是,这并没有帮助,因为Spring会自动查找文件夹 src / main / resources 。这对我不起作用,因为我的项目结构不允许我添加此文件夹并在其中放入XML文件。如果我尝试创建这个文件夹,那么它会自动放入Java-resources文件夹中,Eclipse不允许我将XML放在那里。

这是我的项目的样子: enter image description here

有没有办法让我声明Spring应该在哪里寻找这个spring.xml文件?

4 个答案:

答案 0 :(得分:1)

ClassPathXmlApplicationContext假定该文件位于类路径中(Javy描述了如何从类路径加载资源)。​​

如果要从文件系统加载配置(正如您所做的那样),您可能需要考虑使用FileSystemXmlApplicationContext。使用此机制加载上下文,您可以像当前一样传递文件系统位置。

答案 1 :(得分:0)

new ClassPathXmlApplicationContext(this.getClass().getResource("/spring.xml").getPath())

尝试上面的代码

希望有所帮助

答案 2 :(得分:0)

Spring不会查看src/main/resources,它会查看类路径。

如果您撰写projectName/spring.xml,则需要在bin/projectName/spring.xmlbuild/projectName/spring.xml中提交此文件。您的构建文件夹binbuild的位置。

如果您构建jar,则此文件应位于jar!projectName/spring.xml中。

对于Web应用程序,此文件应位于WEB-INF/classes/projectName/spring.xml中。

如果在类路径中添加src/main/resources,则此文件夹的内容将位于构建文件夹中。 Maven会自动在类路径中添加src/main/resources

有时您应该在IDE中重建(清理)项目以在build文件夹中包含此类文件。

答案 3 :(得分:0)

使用“ FileSystemXmlApplicationContext”作为

ApplicationContext  context =  new FileSystemXmlApplicationContext("spring.xml");