首页 新闻 会员 周边 捐助

spring mvc 整合mybatis dao接口注入失败

1
悬赏园豆:80 [待解决问题]

错误信息:

 

严重: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxq.serviceimp.UserServiceImpl com.xxq.controller.UserController.userInfoServiceImpl; nested exception is 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 com.xxq.mapper.UserDAO com.xxq.serviceimp.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxq.mapper.UserDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

 

 

 

代码目录如下

 

UserController.java

package com.xxq.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.xxq.po.User;
import com.xxq.serviceimp.UserServiceImpl;

@Controller
public class UserController {
    @Autowired
    private UserServiceImpl userInfoServiceImpl;

    /*
     * 获取用户 + 分页 + 按账号姓名筛选
     */
    @RequestMapping(value = "/getUsers")
    public String getAllUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 分页,easyui-datagrid会自动传递页码page和页长size
        int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        int rows = request.getParameter("rows") == null ? 10 : Integer.parseInt(request.getParameter("rows"));
        // 筛选条件
        String search_name = request.getParameter("search_name") == null ? "" : request.getParameter("search_name");
        String search_account = request.getParameter("search_account") == null ? ""
                : request.getParameter("search_account");
        // 调用服务
        List<User> users = userInfoServiceImpl.getAllUsers(page, rows, search_name, search_account);
        // 封装json数据,total存放数据总数,rows存放数据数组,以提供给easyui的datagrid
        JSONObject json = new JSONObject();
        // 筛选后的总数
        json.put("total", userInfoServiceImpl.getCount(search_name, search_account));
        JSONArray row = new JSONArray();
        for (User info : users) {
            JSONObject jo = new JSONObject();
            jo.put("id", info.getId());
            jo.put("account", info.getAccount());
            jo.put("name", info.getName());
            jo.put("phone", info.getPhone());
            jo.put("email", info.getEmail());
            jo.put("address", info.getAddress());
            row.put(jo);
        }
        json.put("rows", row);
        System.out.println(json.toString());
        // 写入响应
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(json.toString());
        // 没有对应jsp文件,故直接返回null
        return null;
    }
}

 

UserDAO.java

package com.xxq.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import com.xxq.po.User;
@Repository
public interface UserDAO {
    // 取全部用户 + 分页 + 按条件匹配
    public List<User> getAllUsers(@Param("skip") int skip, @Param("size") int size,
            @Param("search_name") String search_name, @Param("search_account") String search_account);

    // 用户数量
    public int getCount(@Param("search_name") String search_name, @Param("search_account") String search_account);

    // 添加用户
    public int addUser(User user);

    // 更新
    public int updateUser(User user);

    // 删除
    public int deleteUserById(int id);
}

 

userDaoMapper.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="com.xxq.mapper.UserDAO"> 
    <!-- 用户总数 + 账号和名称匹配 -->
    <select id="getCount" resultType="int"> 
        select count(*) from user where name like #{search_name} and account like #{search_account}
    </select>
    <!-- 查询用户 + 分页 + 按账号和名称匹配 -->
    <select id="getAllUsers" resultType="User"> 
        select * from user where name like #{search_name} and account like #{search_account} limit #{skip},#{size}
    </select>  
    <!--新增用户 -->
    <insert id="addUser" parameterType="User">
        insert into user(name,account,phone,email,address) values(#{name},#{account},#{phone},#{email},#{address});
    </insert>
    <!-- 更新用户 -->
    <update id="updateUser" parameterType="User">
        update user set name=#{name},account=#{account},phone=#{phone},email=#{email},address=#{address} where id=#{id}
    </update>
    <!--删除用户 -->
    <delete id="deleteUserById" parameterType="int">
         delete from user where id=#{id}
    </delete>
</mapper>  

UserService

package com.xxq.service;

import java.util.List;

import com.xxq.po.User;

public interface UserService {
 
    public List<User> getAllUsers(int pageNo, int size, String search_name, String search_account);
    /**
     * 用户数量
     * @return
     */
    public int getCount(String search_name, String search_account);
    /**
     * 新增用户
     * @param user
     * @return
     */
    public int addUser(User user);
    /**
     * 更新用户
     * @param user
     * @return
     */
    public int updateUser(User user);
    /**
     * 删除用户
     * @param id
     * @return
     */
    public int deleteUserById(int id);
}

 

UserServiceImpl

package com.xxq.serviceimp;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.xxq.mapper.UserDAO;
import com.xxq.po.User;
import com.xxq.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDao;
   

    // 获取用户数量 + 按账号姓名匹配
    public int getCount(String search_name, String search_account) {
        // TODO Auto-generated method stub
       
       
        return userDao.getCount("%" + search_name + "%", "%" + search_account + "%");
    }

    // 获取用户 + 分页 + 按账号姓名匹配
    public List<User> getAllUsers(int pageNo, int size, String search_name, String search_account) {
        // TODO Auto-generated method stub
        return userDao.getAllUsers((pageNo - 1) * size, size, "%" + search_name + "%", "%" + search_account + "%");
    }

    // 添加用户
    public int addUser(User user) {
        // TODO Auto-generated method stub
        return userDao.addUser(user);
    }

    // 更新用户
    public int updateUser(User user) {
        // TODO Auto-generated method stub
        return userDao.updateUser(user);
    }

    // 删除指定id用户
    public int deleteUserById(int id) {
        // TODO Auto-generated method stub
        return userDao.deleteUserById(id);
    }
}

 

配置文件如下:

mybatisconfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias type="com.xxq.po.User" alias="user" />
    </typeAliases>
</configuration>

 

spring-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
    <!--配置数据库连接属性 -->
    <!--配置数据库连接属性加载db.properties的数据库连接信息文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="30" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据库连接对象 -->
        <property name="dataSource" ref="dataSource" />
        <!--加载mybatis配置文件 这里mybatis配置文件的工作都在spring中配置了所以mybatis只是配置别名就可以 -->
        <property name="configLocation" value="classpath:config/mybatis/mybatisconfig.xml" />
        <!--指定sql映射xml文件的路径 -->
        <property name="mapperLocations" value="classpath:com/xxq/mapper/UserDAOMapper.xml"></property>
    </bean>

    <!-- mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描的包,如果要扫描多个,中间用,隔开 -->
        <property name="basePackage" value="com.xxq.mybatis.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!--定义事物管理器,由spring管理事务 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

 

spring-mvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
    <!--打开注解 -->
    <mvc:annotation-driven/>
    <!--可以访问静态文件 -->
    <mvc:default-servlet-handler/>
    <!--配置扫描包 -->
    <context:component-scan base-package="com.xxq"/>

    <!--内部视图解析器,JSP与JSTL模板 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--指定视图渲染类 -->
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <!--自动添加到路径中的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!--自动添加到路径中的后缀 -->
        <property name="suffix" value=".jsp" />
        <!--设置所有视图的内容类型,如果视图本身设置内容类型视图类可以忽略 -->
        <property name="contentType" value="text/html;charset=UTF-8" />
    </bean>

</beans>

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://java.sun.com/xml/ns/javaee" 
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
         id="WebApp_ID" version="3.0">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

 
   <listener>
        <description>Spring容器加载监听器</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <description>设置Spring加载时的配置文件位置,默认位置在WEB-INF/lib目录下</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:config/spring/spring-dao.xml</param-value>
        
    </context-param>
    <!-- 加载spring配置文件 -->  
    <servlet>  
        <servlet-name>springmvc</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:config/spring/spring-mvc.xml</param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>  

    <!-- 设置url匹配模式 -->  
    <servlet-mapping>  
        <servlet-name>springmvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  

    <!-- 编码过滤器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>utf-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
    </filter> 

    <!-- 路径映射 --> 
    <filter-mapping>  
        <filter-name>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping> 
</web-app>  

 

 

 

 

 

 StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xxq.serviceimp.UserServiceImpl com.xxq.controller.UserController.userInfoServiceImpl; nested exception is 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 com.xxq.mapper.UserDAO com.xxq.serviceimp.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xxq.mapper.UserDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1269)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1182)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1072)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5368)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5660)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1571)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1561)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

924249386的主页 924249386 | 初学一级 | 园豆:122
提问于:2018-05-22 23:58
< >
分享
所有回答(4)
0
不会摇头的风扇 | 园豆:443 (菜鸟二级) | 2018-05-23 10:23
0

配置spring不扫描controller的包

配置springMVC只扫描controller的包

、熙和 | 园豆:1508 (小虾三级) | 2018-05-23 12:21

朋友,能详细解释一下吗,看不懂

支持(0) 反对(0) 924249386 | 园豆:122 (初学一级) | 2018-05-23 12:36

@924249386:

spring和springMVC扫描区分一下, 具体原因去百度搜索 spring springmvc 扫描
这里也要改一下:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxq.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

还有UserDAO接口里面把@Repository注解去掉; 你这个UserDAO是接口加这个注解做什么

支持(0) 反对(0) 、熙和 | 园豆:1508 (小虾三级) | 2018-05-23 14:22

@、熙和:朋友,spring和springMVC扫描的区分我了解了,已整改,没有效果。下边这个需要改什么?

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxq.mapper" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

支持(0) 反对(0) 924249386 | 园豆:122 (初学一级) | 2018-05-23 21:23

@924249386:
这个是你上面贴的
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描的包,如果要扫描多个,中间用,隔开 -->
<property name="basePackage" value="com.xxq.mybatis.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

这里改成 value="com.xxq.mapper" , 这个是配置扫描Dao接口的路径
UserDAO接口去掉@Repository注解

支持(0) 反对(0) 、熙和 | 园豆:1508 (小虾三级) | 2018-05-24 10:35
0

UserDAO 这个类用@MapperScan(basePackages = { "com.cml.springboot.sample.db" }, sqlSessionFactoryRef = "sqlSessionFactory") 类似于这种方式注解才能配合你的spring-dao.xml

或者你可以试试这种写法

<mybatis:scan base-package="你的mapper地址" factory-ref="sqlSessionFactory"/>

让我发会呆 | 园豆:2929 (老鸟四级) | 2018-05-23 13:35

朋友,能详细点吗?这个问题困扰了我好久

支持(0) 反对(0) 924249386 | 园豆:122 (初学一级) | 2018-05-23 21:26

@924249386: 就是你的dao没有注入进去,把你的mapper扫描器改成这种写法<mybatis:scan base-package="你的mapper地址" factory-ref="sqlSessionFactory"/>

支持(0) 反对(0) 让我发会呆 | 园豆:2929 (老鸟四级) | 2018-05-23 21:28

@让我发会呆: 朋友,非常感谢你的回复,我按你的要求改了

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.2.xsd 
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
    
     <context:component-scan base-package="com.xxq"/>   
    <!--配置数据库连接属性 -->
    <!--配置数据库连接属性加载db.properties的数据库连接信息文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="30" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据库连接对象 -->
        <property name="dataSource" ref="dataSource" />
        <!--加载mybatis配置文件 这里mybatis配置文件的工作都在spring中配置了所以mybatis只是配置别名就可以 -->
        <property name="configLocation" value="classpath:config/mybatis/mybatisconfig.xml" />
        <!--指定sql映射xml文件的路径 -->
        <property name="mapperLocations" value="classpath:com/xxq/mapper/UserDAOMapper.xml"></property>
    </bean>

    <!-- mapper扫描器 -->
<!--     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        扫描的包,如果要扫描多个,中间用,隔开
        <property name="basePackage" value="com.xxq.mybatis.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean> -->
<mybatis:scan base-package="com.xxq.mybatis.mapper" factory-ref="sqlSessionFactory"/>
    <!--定义事物管理器,由spring管理事务 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

xml 就报错,提示Multiple annotations found at this line:
    - The prefix "mybatis" for element "mybatis:scan" is not

支持(0) 反对(0) 924249386 | 园豆:122 (初学一级) | 2018-05-23 21:43

@924249386: 可能是少些东西吧,你再试试这样配置下

<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations">
<list>
<value>classpath*:mybatis/mapper/**/*.xml</value>
</list>
</property>
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
</bean>

<!-- DAO接口所在包名,Spring会自动查找其下的类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.effective.dao.mapper.gen" />
</bean>

支持(0) 反对(0) 让我发会呆 | 园豆:2929 (老鸟四级) | 2018-05-23 22:00

@924249386: 你这个xml报错问题,可能是你的这个xml少了些约束吧,你试试我这个

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx" 

xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://mybatis.org/schema/mybatis-spring                    http://mybatis.org/schema/mybatis-spring.xsd

http://www.springframework.org/schema/tx            http://www.springframework.org/schema/tx/spring-tx.xsd">

支持(0) 反对(0) 让我发会呆 | 园豆:2929 (老鸟四级) | 2018-05-24 08:42

@让我发会呆: 朋友非常感谢,代码没问题,是jdk版本的问题1.8换到1.7就好了

支持(0) 反对(0) 924249386 | 园豆:122 (初学一级) | 2018-05-24 17:23
0

注入interface,不要注入实现类

杜晓洋 | 园豆:55 (初学一级) | 2018-05-24 09:59

下回仔细点,控制台的异常信息已经说的很清楚了

支持(0) 反对(0) 杜晓洋 | 园豆:55 (初学一级) | 2018-05-24 10:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册