spring could not autowired field.

spring不能自动装配,这问题我在网上搜索了很久,但是都没有适合我的答案。
以下是报错信息

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private cat.dao.UserMapper cat.service.UserServiceImpl.userMapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [cat.dao.UserMapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: ...

    ... 61 more

目录结构:

clipboard.png

UserController

  package cat.controller;

/**
    • Created by xugenli on 16/4/9.
      */

    1. javax.annotation.Resource;

    2. javax.servlet.http.HttpServletRequest;

    3. cat.domain.User;

    4. cat.service.UserService;

    5. org.apache.ibatis.annotations.Param;

    6. org.springframework.beans.factory.annotation.Autowired;

    7. org.springframework.stereotype.Controller;

    8. org.springframework.ui.Model;

    9. org.springframework.web.bind.annotation.PathVariable;

    10. org.springframework.web.bind.annotation.RequestMapping;

      @Controller

    11. class UserController {

         @Autowired
         private UserService userService;
      
         @RequestMapping(value = "/show/{id}")
         public String toIndex(@PathVariable("id") Integer id, Model model) {
             User user = userService.showUser(id);
             model.addAttribute("user", user);
             return "/showUser";
         }

      }

    UserMapper:

    package cat.dao;
    
    
    import cat.domain.User;
    
    public interface UserMapper {
        int deleteByPrimaryKey(Integer id);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        User selectByPrimaryKey(Integer id);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    }

    User:

    package cat.domain;
    
    public class User {
        private Integer id;
    
        private String userName;
    
        private String password;
    
        private Integer age;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName == null ? null : userName.trim();
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password == null ? null : password.trim();
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }

    UserMapper.xml:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="cat.dao.UserMapper" >
      <resultMap id="BaseResultMap" type="cat.domain.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
      </resultMap>
      <sql id="Base_Column_List" >
        id, user_name, password, age
      </sql>
        <select id="selectByPrimaryKey" resultType="hashMap" parameterType="int" >
            select *
            from user_t
            where id = #{id}
        </select>
      <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
        delete from user_t
        where id = #{id,jdbcType=INTEGER}
      </delete>
      <insert id="insert" parameterType="cat.domain.User" >
        insert into user_t (id, user_name, password, 
          age)
        values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
          #{age,jdbcType=INTEGER})
      </insert>
      <insert id="insertSelective" parameterType="cat.domain.User" >
        insert into user_t
        <trim prefix="(" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            id,
          </if>
          <if test="userName != null" >
            user_name,
          </if>
          <if test="password != null" >
            password,
          </if>
          <if test="age != null" >
            age,
          </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
          <if test="id != null" >
            #{id,jdbcType=INTEGER},
          </if>
          <if test="userName != null" >
            #{userName,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            #{password,jdbcType=VARCHAR},
          </if>
          <if test="age != null" >
            #{age,jdbcType=INTEGER},
          </if>
        </trim>
      </insert>
      <update id="updateByPrimaryKeySelective" parameterType="cat.domain.User" >
        update user_t
        <set >
          <if test="userName != null" >
            user_name = #{userName,jdbcType=VARCHAR},
          </if>
          <if test="password != null" >
            password = #{password,jdbcType=VARCHAR},
          </if>
          <if test="age != null" >
            age = #{age,jdbcType=INTEGER},
          </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
      </update>
      <update id="updateByPrimaryKey" parameterType="cat.domain.User" >
        update user_t
        set user_name = #{userName,jdbcType=VARCHAR},
          password = #{password,jdbcType=VARCHAR},
          age = #{age,jdbcType=INTEGER}
        where id = #{id,jdbcType=INTEGER}
      </update>
    
    
    
    
      
    </mapper>

    UserService:

    package cat.service;
    
    import cat.domain.User;
    import org.springframework.stereotype.Repository;
    
    /**
     * Created by on 16/4/9.
     */
    public interface UserService {
        User showUser(int id);
    }

    UserServiceImpl:

    package cat.service;
    
    
    import cat.dao.UserMapper;
    import cat.domain.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    /**
     * Created by  on 16/4/9.
     */
    @Service
    public class UserServiceImpl {
    
        @Autowired
       private UserMapper userMapper;
    
    
        public User showUser(int id){
            return userMapper.selectByPrimaryKey(id);
        }
    }

    clipboard.png

    spring-mvc.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
        <context:component-scan base-package="cat.controller" />
        <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
        <bean id="mappingJacksonHttpMessageConverter"
              class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    
        <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
        </bean>
    
        <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
        <bean id="multipartResolver"
              class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 默认编码 -->
            <property name="defaultEncoding" value="utf-8" />
            <!-- 文件大小最大值 -->
            <property name="maxUploadSize" value="10485760000" />
            <!-- 内存中的最大值 -->
            <property name="maxInMemorySize" value="40960" />
        </bean>
    
    
    
    
        <mvc:default-servlet-handler/>
    
    
    
    </beans>

    spring-mybatis.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
    
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                            http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                            http://www.springframework.org/schema/context
                            http://www.springframework.org/schema/context/spring-context-3.1.xsd
                            http://www.springframework.org/schema/mvc
                            http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
        <!-- 自动扫描 -->
        <context:component-scan base-package="cat"/>
    
    
    
        <!-- 引入配置文件 -->
        <bean id="propertyConfigurer"
              class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:jdbc.properties" />
        </bean>
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
              destroy-method="close">
            <property name="driverClassName" value="${driver}" />
            <property name="url" value="${url}" />
            <property name="username" value="${username}" />
            <property name="password" value="${password}" />
            <!-- 初始化连接大小 -->
            <property name="initialSize" value="${initialSize}"></property>
            <!-- 连接池最大数量 -->
            <property name="maxActive" value="${maxActive}"></property>
            <!-- 连接池最大空闲 -->
            <property name="maxIdle" value="${maxIdle}"></property>
            <!-- 连接池最小空闲 -->
            <property name="minIdle" value="${minIdle}"></property>
            <!-- 获取连接最大等待时间 -->
            <property name="maxWait" value="${maxWait}"></property>
        </bean>
    
        <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 自动扫描mapping.xml文件 -->
            <property name="mapperLocations" value="classpath*:cat/mapping/*.xml" ></property>
        </bean>
    
        <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="dao" />
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
        </bean>
    
    
    
        <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource" />
        </bean>
    
    
    
    
    
    
    </beans>

    这问题卡了挺久了,我知道就是某一处的小错误,不过就是找不出来=。=

    UPDATE:

    修改了配置文件:

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

    <property name="basePackage" value="cat.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

    </bean>

    clipboard.png

    clipboard.png

    启动成功,但是编译还是有红线。。。

    阅读 7.5k
    3 个回答

    spring-mybatis.xml里面的mapperScanner的basePackage应该是cat.dao

    报错上看是Mapper没创建成功。
    <property name="basePackage" value="dao" />
    这里配置有问题,value应该写上Mapper所在的包名,改为:
    <property name="basePackage" value="cat.dao" />

    mapper接口和XML放在同包,然后扫描basepackage 指向这个包,XML里namespace 也指向这个包

    撰写回答
    你尚未登录,登录后可以
    • 和开发者交流问题的细节
    • 关注并接收问题和回答的更新提醒
    • 参与内容的编辑和改进,让解决方法与时俱进
    推荐问题