使用SpringMVC+Mybatis时,无法注入service

spring-mvc.xml中如下:



/context:component-scan
我明明扫描了所有的包为什么还是找不到,出现如下异常:

九月 03, 2017 4:41:52 下午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Allocate exception for servlet spring
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.lyj.bookmanage.service.IUserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}

这是service
这是controller

@resource默认按照名称进行装配,Dao层的那个没贴就不说了,但是你的UserServiceImpl示例化后应该是userServiceImpl啊,哪有userService?

@service注解时,默认别名就是当前类名,但是首字母小写,如果要定义别名用@service('userService')形式!

题主这个适合用@Autowired注入

  1. @Autowired @Autowired是Spring 提供的,需导入 Package:org.springframework.beans.factory.annotation.Autowired; 只按照byType 注入。
  2. @Resource
    @Resource默认按 byName 自动注入,是J2EE提供的, 需导入Package:

    javax.annotation.Resource;
    @Resource有两个中重要的属性:name和type ,而Spring将@Resource注解的name属性解析为bean的
    名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用
    type属性时则使用 byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用by
    Name自动注入策略。

    参考链接:http://blog.csdn.net/angus_17/article/details/7543478
    

Controller里面的@Resource改为@Autowired,userService改为iUserService

Service里面的@Service改为@Service("iUserService")

就ok了

你看下你的扫描路径对没对

首先你如果不用set方法注入的话,建议使用@Autowired,把@resource那个换成@Autowired即可,只要能实现接口,是可以这样注解的