Spring - applicationContext.xml cannot be opened because it does not exist
I have a Spring MVC application and a problem with JUnit tests combined with the file applicationContext.xml.
In my JUnit test class I write:
final ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
service = (TestServiceImpl) context.getBean("testServiceImpl");
The error I get is that aplicationContect.xml can not be found:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
But it exists in the WEB-INF folder.
So, what's wrong here? Why does the file not exist for the JUnit test?
Solution 1:
You should keep your Spring files in another folder, marked as "source" (just like "src" or "resources").
WEB-INF is not a source folder, therefore it will not be included in the classpath (i.e. JUnit will not look for anything there).
Solution 2:
If you use maven, create a directory called resources
in the main directory, and then copy your applicationContext.xml
into it.
From your java code call:
ApplicationContext appCtx = new ClassPathXmlApplicationContext("applicationContext.xml");
Solution 3:
I got the same error.
I solved it moving the file applicationContext.xml
in a
sub-folder of the src
folder. e.g:
context = new ClassPathXmlApplicationContext("/com/ejemplo/dao/applicationContext.xml");