上下文不存在



我对spring上下文有一个非常奇怪的问题。

public static void main(String[] args) {

    File file = new File("/home/user/IdeaProjects/Refactor/src/spring-cfg.xml");
    System.out.println("Exist "+file.exists());
    System.out.println("Path "+file.getAbsoluteFile());
    ApplicationContext context = new ClassPathXmlApplicationContext(file.getAbsolutePath());

显示在控制台上:

Exist true
Path /home/user/IdeaProjects/Refactor/src/spring-cfg.xml
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [home/user/IdeaProjects/Refactor/src/spring-cfg.xml]; nested exception is java.io.FileNotFoundException: class path resource [home/user/IdeaProjects/Refactor/src/spring-cfg.xml] cannot be opened because it does not exist

您试图加载它,如果/home/user/IdeaProjects/Refactor/src/spring-cfg.xml是类路径上的资源-它不是,它只是一个常规文件。试着用FileSystemXmlApplicationContext代替…或者指定一个真正的类路径资源,例如,只要spring-cfg.xml假设你的src目录在你的类路径。

这并不奇怪。您正在尝试从一个不存在的文件中读取上下文。

ClassPathXmlApplicationContext,如其名,不使用路径作为绝对路径,而是在类路径中查找。你应该使用

ApplicationContext context = new ClassPathXmlApplicationContext("/spring-cfg.xml");

注意:这将不会从src中读取文件,而是从编译后的类中读取文件(在编译时应该复制到这些类中)。

来自异常的消息是正确的,/home/user/IdeaProjects/Refactor/src/spring-cfg.xml不是类路径资源(看起来像您机器中的常规路径)。

我建议使用:ClassPathXmlApplicationContext("classpath:spring-cfg.xml"),因为你的配置xml看起来像在你的源文件夹

我认为这段代码可以工作

ApplicationContext context = 
    new FileSystemXmlApplicationContext("file:/home/user/IdeaProjects/Refactor/src/spring-cfg.xml");

您可以在这里找到一些有用的信息http://static.springsource.org/spring/docs/2.5.6/reference/resources.html

最新更新