Spring cannot find bean xml configuration file when it does exist

Thanks, but that was not the solution. I found it out why it wasn’t working for me.

Since I’d done a declaration:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

I thought I would refer to root directory of the project when beans.xml file was there.
Then I put the configuration file to src/main/resources and changed initialization to:

ApplicationContext context = new ClassPathXmlApplicationContext("src/main/resources/beans.xml");

it still was an IO Exception.

Then the file was left in src/main/resources/ but I changed declaration to:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

and it solved the problem – maybe it will be helpful for someone.

thanks and cheers!

Edit:

Since I get many people thumbs up for the solution and had had first experience with Spring as student few years ago, I feel desire to explain shortly why it works.

When the project is being compiled and packaged, all the files and subdirs from ‘src/main/java’ in the project goes to the root directory of the packaged jar (the artifact we want to create). The same rule applies to ‘src/main/resources’.

This is a convention respected by many tools like maven or sbt in process of building project (note: as a default configuration!). When code (from the post) was in running mode, it couldn’t find nothing like “src/main/resources/beans.xml” due to the fact, that beans.xml was in the root of jar (copied to /beans.xml in created jar/ear/war).

When using ClassPathXmlApplicationContext, the proper location declaration for beans xml definitions, in this case, was “/beans.xml”, since this is path where it belongs in jar and later on in classpath.

It can be verified by unpacking a jar with an archiver (i.e. rar) and see its content with the directories structure.

I would recommend reading articles about classpath as supplementary.

Leave a Comment