4

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

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
4

4 回答 4

3

您正在尝试加载它,就好像它/home/user/IdeaProjects/Refactor/src/spring-cfg.xml是类路径上的资源一样 - 它不是,它只是一个常规文件。尝试使用FileSystemXmlApplicationContext...或指定一个真正的类路径资源,例如spring-cfg.xml假设您的src目录在您的类路径中。

于 2013-06-11T20:39:49.460 回答
2

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

ClassPathXmlApplicationContext,名副其实,不使用绝对路径,而是在类路径中寻找。你应该使用

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

注意:这将不是从编译的类而是从编译的类中读取文件src(在编译时它应该被复制到那里)。

于 2013-06-11T20:40:49.463 回答
0

我认为这段代码会起作用

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

于 2013-06-11T21:00:17.057 回答
0

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

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

于 2013-06-11T20:39:34.193 回答