Failed to load ApplicationContext

在开发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时找不到类。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值