步骤:
1、设置包扫描、引入外部属性文件(数据源配置)(若不引入可以直接在Spring的数据源配置中直接指定)
2、设置数据源
3、设置Spring事务管理器
4、配置基于注解的事务
5、配置SqlSessionFactory对象,设置MyBatis配置文件的位置、Mapper.XML文件的位置、数据源、别名……
5、配置Mapper接口扫描
例如:
<?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>