Context does not exist

I have a very strange spring context problem.

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 
+4
source share
4 answers

You are trying to load it, as if /home/user/IdeaProjects/Refactor/src/spring-cfg.xml was a resource in the class path - it is not, it is a regular file. Instead, use FileSystemXmlApplicationContext ... or specify an authentic class path resource, for example. just spring-cfg.xml , assuming your src directory is in your class path.

+3
source

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

True to its name, ClassPathXmlApplicationContext does not use the path as an absolute path, but it looks in the class path. You have to use

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

NOTE: this will not read the file from src , but from the compiled classes (where it should have been copied at compile time).

+2
source

The message from the exception is true, /home/user/IdeaProjects/Refactor/src/spring-cfg.xml not a class path resource (looks like a normal path from your computer).

I would suggest using: ClassPathXmlApplicationContext("classpath:spring-cfg.xml") , since your xml configuration file looks like it is in your original folder.

0
source

I think this code will work

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

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

0
source

Source: https://habr.com/ru/post/1485686/


All Articles