Spring整合MyBatis
<?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: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/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--引入外部数据库连接信息配置文件-->
<context:property-placeholder location="classpath:*.properties"/>
<!--加载druid数据库连接池资源,这里使用默认配置-->
<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>
<bean id="accountService" class="com.project.service.impl.AccountServiceImpl">
<!--注入资源bean.这里写ref时报红,
由于这里的值来源于mybatis动态代理实现类,
现在还没有,因此会报红-->
<property name="accountDao" ref="accountDao"/>
</bean>
<!--spring整合mybatis后控制的创建连接用的对象-->
<!--配置SessionFactoryBean-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.project.domain"/>
</bean>
<!--加载mybatis映射配置的扫描,作为spring的bean进行管理-->
<!-- 扫描mapper配置文件的地址 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.project.dao"/>
</bean>
</beans>
总结:
步骤(省略一些前置步骤,只考虑Spring配置文件的编写)
配置数据源bean(DataSource)
配置工厂bean(SqlSessionFactoryBean)
配置mapper扫描bean(MapperScannerconfiguer)
配置业务层bean(注入mapper对象)