背景
将eclipse中的项目重写到idea中。
(1)SpringMVC的配置文件问题(路径问题)。
(2)Spring配置文件加载问题(引起后来的空指针问题),在进行单元测试的时候,通过MockMvc,虚拟一个mvc请求,但是在调试过程中发现MockMvc的对象mockMvc一直报空指针异常。
1,SpringMVC配置文件路径问题:
(1),刚开始SpringMVC的配置文件使用默认的路径引入爆红线,最后将springMvc的配置文件也放倒了classpath下。(问题解决)
①,刚开始(默认路径及默认文件名)
//idae中这样引入file后面一直爆红,(eclipse中正常)
@ContextConfiguration(locations= {"classpath:applicationContext.xml","filesrc/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
解决方法:修正如下,将dispatcherServlet-servlet.xml也放到类路径下
//这样引入就不爆红线了
@ContextConfiguration(locations= {"classpath:applicationContext.xml","classpath:dispatcherServlet-servlet.xml"})
2,Spring文件加载失败问题:
(2),一直产生ApplicationContext Load Fail或者MockMvc空指针异常
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations= {"classpath:applicationContext.xml","classpath:dispatcherServlet-servlet.xml"})
public class MVCTest {
//传入Springmvc的ioc
@Autowired
WebApplicationContext context;
//虚拟mvc请求,获取到处理结果
MockMvc mockMvc;
@Before
public void initMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testPage() throws Exception {
//模拟请求,并拿到返回值,此处一直抛出mockMvc空指针异常
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "1")).andReturn();
//请求成功后,取出请求域中的值(比如说之前放入的pageInfo,我们可以取出pageInfo进行验证)
MockHttpServletRequest request = result.getRequest();
/*
一部分正常的分页操作
*/
}
}
发现问题:因为是对以前项目的一个复习,所以重新翻看了之前的spring配置文件
(1), 现在我的写法(错误,导致配置文件加载失败)
<!-- 1,配置让spring除了控制器不扫描,其余的都扫描-->
<context:component-scan base-package="crud" use-default-filters="false">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
(2),以前项目中的写法(正确)
<!--配置让spring除了控制器不扫,其他的都扫描-->
<context:component-scan base-package="crud" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
这两个问题我都没有找到报错的原因,spring配置文件中使用context:include-filter而没有使用context:exclude-filter标签就导致了文件加载失败,我也是很迷。