user902691
user902691

Reputation: 1159

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

Upvotes: 4

Views: 1424

Answers (4)

Tuna
Tuna

Reputation: 3005

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

Upvotes: 0

SJuan76
SJuan76

Reputation: 24885

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).

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500525

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, e.g. just spring-cfg.xml assuming that your src directory is in your classpath.

Upvotes: 3

user180100
user180100

Reputation:

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.

Upvotes: 0

Related Questions