繁体   English   中英

上下文不存在

[英]Context doesn't exist

春天语境我有一个非常奇怪的问题。

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 ,其名称为true,不使用路径作为绝对路径,但它在类路径中寻找。 你应该用

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

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

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

我建议使用: ClassPathXmlApplicationContext("classpath:spring-cfg.xml")因为你的config 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM