简体   繁体   中英

Context doesn't exist

I have very strange problem with spring context.

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());

Show on console:

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

You're trying to load it as if /home/user/IdeaProjects/Refactor/src/spring-cfg.xml is a resource on the classpath - it's not, it's just a regular file. Try using FileSystemXmlApplicationContext instead... or specify a genuine classpath resource, eg just spring-cfg.xml assuming that your src directory is in your classpath.

It is not very strange. You are trying to read the context from a file that does not exist.

ClassPathXmlApplicationContext , true to its name, does not use the path as an absolute one but it seeks in the classpath. You should use

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

NOTE: this will read the file not from src but from the compiled classes (where it should have been copied to while compiling).

The message from the exception is correct, /home/user/IdeaProjects/Refactor/src/spring-cfg.xml is not a classpath resource (looks like a regular path from your machine).

I would advise using: ClassPathXmlApplicationContext("classpath:spring-cfg.xml") as your config xml looks like being in your source folder.

I think this code will work

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

You can find some helpful information here http://static.springsource.org/spring/docs/2.5.6/reference/resources.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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