Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

I am trying to set the configuration location for my Project but I keep getting the following error:

java.io.FileNotFoundException: class path resource [main/resources/app-context.xml] cannot be opened because it does not exist

I have my project set up like this:

enter image description here

And I have my code set up as:

ApplicationContext context = new ClassPathXmlApplicationContext(configLocation: "main/resources/app-context.xml"); 

How can I fix this?

like image 369
Rob_kael Avatar asked Mar 17 '17 17:03

Rob_kael


People also ask

How do I stop FileNotFoundException in Java?

How to avoid FileNotFoundException in java? Please ensure file exists when you try to read from file from path exists (using FileInputStream) to avoid FileNotFoundException. Please ensure file exists when we try to acces file from invalid path using RandomAccessFile to avoid FileNotFoundException.

Where is classpath in spring?

This special prefix specifies that all classpath resources that match the given name must be obtained (internally, this essentially happens via a ClassLoader. getResources(...) call), and then merged to form the final application context definition. So classpath: starts at the root of your classpath.

What is spring boot classpath?

It's a path inside your project where you place resources. During the build step, Maven will take files in there and place them in the appropriate place for you to use them in your runtime classpath, eg in an executable . jar , some physical file system location used in the classpath (with java 's -cp option), etc.

What is classpath variable?

The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)


2 Answers

What you put directly under src/main/java is in the default package, at the root of the classpath. It's the same for resources put under src/main/resources: they end up at the root of the classpath.

So the path of the resource is app-context.xml, not main/resources/app-context.xml.

like image 136
JB Nizet Avatar answered Sep 22 '22 21:09

JB Nizet


We can also try this solution

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:app-context.xml"); 

in this the spring automatically finds the class in the class path itself

like image 28
Saurabh Verma Avatar answered Sep 23 '22 21:09

Saurabh Verma