无法从src / main / resources加载dispatcher-servlet.xml

时间:2016-03-13 12:49:41

标签: java maven spring-mvc

我的spring mvc webapp有这个结构(Maven项目):

src
- main
 -- java
 -- webapp 
  --- WEB-INF
   --- web.xml
   --- mvc-dispatcher-servlet.xml

我决定编写单元测试(junit)。在一篇文章中我读到我应该将mvc-dispatcher-servlet.xml移动到src / main / resources,以便我可以在我的测试中在ContextConfiguration注释中访问它:

@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);
    }
}

工作正常,我的单元测试运行成功。比我启动我的应用程序服务器实现更多功能,但我得到例外。我想,在将mvc-dispatcher-servlet.xml从WEB-INF移动到src / main / resources后,我忘了在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>

但我仍然遇到以下异常:

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]

我做错了什么?

1 个答案:

答案 0 :(得分:1)

请考虑这个问题的可能解决方案。不幸的是,我不能总结你的方式有什么问题,但这个解决方案应该有效。

将contextConfigLocation的描述从context-param标记移动到servlet标记内的init-param标记,如下所示:

<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>