Reputation: 11
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.
Upvotes: 1
Views: 87
Reputation: 117
Spring will look for AppConfig.xml
directly in the root of the file path, which is where it should be after being copied from src/main/resources
.
You face the issue due to your incorrect file path. To solve this issue update your file path as follows:
ApplicationContext context = new ClassPathXmlApplicationContext("AppConfig.xml");
Upvotes: 0
Reputation: 16529
By seeing your project image, there are need for corrections :
Move /resource
directory from src/main/java/in/sp/
to /src/main
After moving, change directory name from /resource
to /resources
because Maven follows this directory pattern for resources => /src/main/resources
There is no AppConfig.xml. I see there is ApplicationConfig.xml. Please use that.
Modify to this
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:ApplicationConfig.xml");
Note: Keep your java files under /src/main/java/{package}/
Upvotes: 1