Reputation: 961
My spring mvc webapp had this structure (Maven project):
src
- main
-- java
-- webapp
--- WEB-INF
--- web.xml
--- mvc-dispatcher-servlet.xml
Than I decided to write unit tests(junit). In an article I read that I should move the mvc-dispatcher-servlet.xml to src/main/resources so that I can access it here in my test in the ContextConfiguration annotation:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/mvc-dispatcher-servlet.xml")
public class UserDaoTest {
@Autowired
private UserDao userDao;
@Test
public void testGetUserByUsername() throws Exception {
User admin = userDao.getUserByUsername("admin");
Assert.assertNotNull(admin);
}
}
That worked fine and my unit test was running successfull. Than I started my application server to implement further features but than I got exceptions. I figured out, that after moving the mvc-dispatcher-servlet.xml from WEB-INF to src/main/resources I forgot to make the following change in my web.xml:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- changed from /WEB-INF/mvc-dispatcher-servlet.xml -->
<param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
</context-param>
But I still get the following exception:
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
What did I do wrong?
Upvotes: 1
Views: 704
Reputation: 3346
Please, consider this possible solution to your problem. Unfortunately, I can't conclude what was wrong with your way, but that solution should work.
Move the description of contextConfigLocation from context-param tag to init-param tag inside servlet tag as follows:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- changed from /WEB-INF/mvc-dispatcher-servlet.xml -->
<param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
Upvotes: 1