Search code examples
javaspringmaven

Issue: FileNotFoundException for AppConfig.xml in Spring Project


Project Image

I'm working on a Maven-based Spring project named MavenfirstProject. The folder structure is as follows:

src
├── main
│   ├── java
│   │   └── in.sp.main.App.java
│   └── resources
│       └── AppConfig.xml
└── test

Problem: I keep getting a FileNotFoundException when trying to load the AppConfig.xml file using ClassPathXmlApplicationContext.

Here is the relevant error:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [in/sp/resources/AppConfig.xml]

Caused by: java.io.FileNotFoundException: class path resource [in/sp/resources/AppConfig.xml] cannot be opened because it does not exist

What I've Tried:

File location: The file is placed under src/main/resources, which should be included in the classpath. Loading configuration file: I'm using the following code to load the file:

String file = "in/sp/resources/AppConfig.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(file);

Cleaning and rebuilding the project: I cleaned and rebuilt the project in IntelliJ to ensure the file was correctly copied to target/classes. Observed Behavior: Even after following these steps, the exception persists, and Spring is still trying to look for the file under the in/sp/resources directory instead of in the root classpath.


Solution

  • By seeing your project image, there are need for corrections :

    1. Move /resource directory from src/main/java/in/sp/ to /src/main

    2. After moving, change directory name from /resource to /resources because Maven follows this directory pattern for resources => /src/main/resources

    3. There is no AppConfig.xml. I see there is ApplicationConfig.xml. Please use that.

    4. Modify to this

      ApplicationContext context = new ClassPathXmlApplicationContext("classpath:ApplicationConfig.xml");
      

    Note: Keep your java files under /src/main/java/{package}/