在开发SSM_CRUD的过程中,碰到了一些配置问题导致了Failed to load ApplicationContext,在此记录,以便以后可以引以为戒。
在对查询业务进行单元测试的时候,测试类如下:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations= {"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.xml"})
public class MVCTest {
@Autowired
WebApplicationContext context;
//虚拟mvc请求
MockMvc mockMvc;
@Before
public void initMockMvc() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testPage() throws Exception {
//模拟请求并拿到返回值
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn","1")).andReturn();
//请求成功后,请求域中有pageInfo
MockHttpServletRequest request = result.getRequest();
@SuppressWarnings("unchecked")
PageInfo<Employee> pi = (PageInfo<Employee>) request.getAttribute("pageInfo");
System.out.println("pageNum:"+pi.getPageNum());
System.out.println("pages:"+pi.getPages());
System.out.println("total:"+pi.getTotal());
System.out.println("在页面连续显示的页码:");
int[] nums = pi.getNavigatepageNums();
for(int i:nums) {
System.out.println(""+i);
}
List<Employee> list = pi.getList();
for(Employee e:list) {
System.out.println(e.toString());
}
}
}
最初认为是ContextApplication中locations配置问题,经过检查,并不是这里的问题。
之后在配置文件中发现了问题:
dispatcherServlet-servlet.xml:
……
<!-- springmvc的配置文件 -->
<context:component-scan
base-package="com.zqf.crud" use-default-filters="false">
<!-- 只扫描控制器 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
……
applicationContext.xml:
……
<context:component-scan
base-package="com.zqf.crud">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
……
其中,dispatcherServlet-servlet.xml是SpringMVC配置文件,扫描器要扫描Controller,此时使用了
use-default-filters="false"
而在applicationContext.xml中,扫描器要扫描除Controller之外的文件,这时不能加上面这个参数,否则会报错,而我在写的时候以为二者类似,在后者也加上了use-default-filters="false",因此扫描器无法扫描Service,从而导致在@Autowire时找不到类。