【MyBatis + Spring整合开发】(四)Mapper动态扫描开发

复制上一节中的项目MyBatis_Spring_Mapper,命名为MyBatis_Spring_MapperScaner。

修改Spring主配置文件applicationContext.xml。

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">
    
    <!-- 读取db.properties -->
    <context:property-placeholder location="db.properties"/>
    
    <!-- 配置c3p0连接池 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!-- 配置mybatis sqlSessionFactory -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 配置数据源  -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 告诉spring mybatis的核心配置文件 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"/>
    </bean>
    
    <!-- mapper动态扫描开发 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.test.mapper"/>
    </bean>
    
</beans>

推荐修改MapperTest.java里的一个小细节。

UserMapper mapper = (UserMapper) ac.getBean("userMapper");

改为

UserMapper mapper = ac.getBean(UserMapper.class);

进行测试。

测试结果

本系列【MyBatis + Spring整合开发】到此结束。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容