konosuba 2019-03-11 10:48 采纳率: 100%
浏览 1904
已采纳

springmvc:为什么单元测试却能正常注入service并运行,controller却注入service失败?

这是单元测试

@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包也扫描了...

  • 写回答

4条回答 默认 最新

  • konosuba 2019-03-11 13:33
    关注

    解决了,其实是我没有在web.xml中配置spring。。。这个并不影响单元测试...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 已采纳回答 11月5日

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料