Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [com/main/beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [com/main/beans.xml] cannot be opened because it does not exist
ApplicationContext context =
new ClassPathXmlApplicationContext("com/main/beans.xml");
I have tried before with
ApplicationContext context =
new FileSystemXmlApplicationContext("src/main/java/com/main/beans.xml");
And it works well.
How to do that relative to the classpath?
Note: classpath is in the build path
In the example I'm following, it has the following structure and it works
Project structure
Classpath
ApplicationContext context =
new ClassPathXmlApplicationContext("com/caveofprogramming/spring/test/beans/beans.xml");
Here's the file structure I normally use, which works fine. As @M.Deinum said, you'll want to put your xml file in a src/main/resources
. I normally put to the it in a complete package path with the resources so during compile time, maven will add all the resources to same path as the corresponding classes that use them.
resources get copied to the class package when you do the above
public class App {
public static void main(String[] args) {
ApplicationContext context
= new ClassPathXmlApplicationContext("com/underdogdevs/stackmaven/beans.xml");
Hello hello = (Hello) context.getBean("hello");
hello.sayHello();
}
}
Works fine for me. If you're wondering why you still need to use the complete package name when the xml is already in the same class packages, its it will first be searched for in the class root
UPDATE
put the package with the bean.xml
into the src/main/resources
. It should work with the path your using.
UPDATE 2
"Yes, it worked. But why is it working the example, I'm following as well. If the beans.xml is out of src/main/resources .. I can't find out how that works? *
The thing is, the Spring container will look from the class root. It has nothing to with the resources
folder. The resources
is a convenience dir for maven projects to build to your class path. The reason the tutorial works, is that the beans.xml
is in a package, that will get put into the class path in the build, as seen below. It is only preferred to use a resources
, but a package` will also build to the class path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With