45

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?

Bryan
  • 2,870
  • 24
  • 39
  • 44
Rob_kael
  • 469
  • 1
  • 4
  • 4

7 Answers7

51

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.

metters
  • 533
  • 1
  • 8
  • 17
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • how can add files or update later this resource file when server is running? – Mahdi Jun 03 '17 at 07:04
  • 1
    @Kenji you can't. Resources are application resources, known at compilation time and bundled with the app. If you want to add files later, then those files are not application resources, but data. Data goes in your database, whataver it is (it could be your file system). – JB Nizet Jun 03 '17 at 07:10
  • I want to put a json file for my mobile app version ( force update or not). so if I could just put a json file and update it in public static root, it seems better than create an table for just one record. what is your idea? – Mahdi Jun 03 '17 at 07:14
  • What if I want to locate a file on the same level as "src", in a directory called report? – powder366 Nov 07 '17 at 11:34
9

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

Saurabh Verma
  • 627
  • 1
  • 14
  • 27
2

Try this:

ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
Mouad EL Fakir
  • 3,609
  • 2
  • 23
  • 37
1

The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.

Gomsy
  • 96
  • 6
0

This worked for me ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

0

For Eclipse - Follow the path Build path -> Configure build path -> go to sources -> add folder mark the resource folder where you have your XML file. Now if you try to run it will run just fine.

0

You can use below to read resources. It will give input stream.

InputStream in = MyClass.class.getClassLoader().getResourceAsStream("files.properties");
Pirate
  • 2,886
  • 4
  • 24
  • 42