I'm relatively new to Java and trying to learn spring framework. I have the following code
public class EmployeeTest {
public static void main(String ...args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("my-config.xml");
Employee employee = (Employee) ctx.getBean("emp");
System.out.println(employee.getId());
System.out.println(employee.getName());
}
}
where my-config.xml
is located where the EmployeeTest
class itself is. However, when I'm running this code, I get the following exception:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [my-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [my-config.xml] cannot be opened because it does not exist
I tried to place my-config.xml under src/main/java
as some of the articles suggest, still no luck
I'm using IntelliJ Idea as an editor. Any hints are greatly appreciated
CodePudding user response:
If you use Maven to build your application, you should put the my-config.xml
file to src/main/resources
directory
CodePudding user response:
ok, I found a solution. So I created a resources
directory under src/main
and placed my my-config.xml
there. After it started working
CodePudding user response:
You are using Spring's ClassPathXmlApplicationContext
class. As the name of the class implies (and the javadoc says) this loads its config files from the application classpath.
But the contents of the src/main/java
tree are not on the classpath. Put the file into src/main/resources
... which will (typically) be added directly to the classpath directly, or added to the JAR or WAR file that Maven / Gradle / your IDE generates.
See also:
I tried to place
my-config.xml
undersrc/main/java
as some of the articles suggest, still no luck.
Yea ... no. Unless you do other (probably inadvisable) things, files in the src/main/java
are not on the classpath, and won't be found by ClassPathXmlApplicationContext
.
If those articles really suggested this as a solution for this context, then they are just plain wrong. That approach could sort of work if you were using FileSystemXmlApplicationContext
... but using a relative pathname is fragile (it depends on what the app's working directory is), and a pathname that refers to your source tree typically won't work when you deploy your application in production.