这是单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class mvc {
//@Resource(name="itemServiceMapper")
@Autowired
private ItemService ItemService;
@Test
public void testmapper(){
System.out.println(ItemService.getItemList());
}
}
这是单元测试的运行结果,
但是我在controller里注入却报错...
@Controller
public class ItemController {
//@Resource(name="ItemServiceMapper")
@Autowired
private ItemService ItemService;
@RequestMapping("itemList")
public ModelAndView showItemList()
{
ModelAndView mv=new ModelAndView();
List<Item> list = ItemService.getItemList();
mv.addObject("itemList", list);
mv.setViewName("itemList");
return mv;
}
报错
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'itemController': Unsatisfied dependency expressed through field 'ItemService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'service.ItemService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
讲道理单元测试都成功了,那些配置应该没有错才对啊...
@Service注解也加了,Controller,ServiceImpl包也扫描了...
解决了,其实是我没有在web.xml中配置spring。。。这个并不影响单元测试...
如果你确定你的@Service注解也加了,Controller,ServiceImpl包也扫描了,都扫描到了service的话
那么我猜测的原因可能是缓存之类的,建议把你的开发工具叉掉,然后重启开发工具,把你项目编译的包删除,clean一下,
重新编译一遍,试一下
@Autowired
private ItemService ItemService;// I大写了,应该为小写
@Autowired
private ItemService itemService;
感谢分享,我也是这样的问题,没有在web.xml中配置spring,因为这个困扰了好久,总算解决了(丢脸~)