天天看點

Spring 配置 MyBatis

步驟:

1、設定包掃描、引入外部屬性檔案(資料源配置)(若不引入可以直接在Spring的資料源配置中直接指定)

2、設定資料源

3、設定Spring事務管理器

4、配置基于注解的事務

5、配置SqlSessionFactory對象,設定MyBatis配置檔案的位置、Mapper.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
">

    <!--引入外部屬性檔案(資料源配置)-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--配置掃描base_dictInfo包中不是Controller注解的類-->
    <context:component-scan base-package="com.base_dictInfo" use-default-filters="false">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>

    <!-- 配置Service掃描 -->
    <context:component-scan base-package="com.service"></context:component-scan>
    <context:component-scan base-package="com.mapper"></context:component-scan>

    <!-- 配置資料源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!--配置Spring事務管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置基于注解的事務-->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"></tx:annotation-driven>

    <!-- 配置SqlSessionFactory 對象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定MyBatis核心配置檔案位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 設定資料源 -->
        <property name="dataSource" ref="dataSource" />
        <!--配置Mapper檔案的位置-->
        <property name="mapperLocations" value="classpath:com/mapper/*xml"></property>
    </bean>

    <!-- 配置Mapper檔案掃描 ,掃描Mapper接口的實作,讓這些Mapper能夠自動注入-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.mapper" />
    </bean>
</beans>