<?xmlversion="1.0"encoding="utf8"?>
<beansxmlns="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-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName"default-lazy-init="false">
<!--本示例采用DBCP连接池,应预先把DBCP的jar包复制到工程的lib目录下。
连接池配置如下-->
<beanid="dataSource"class="org.apache.commons.dbcp.BasicDataSource">
<propertyname="driverClassName"value="com.mysql.jdbc.Driver"/>
<propertyname="url"
value="jdbc:mysql://localhost/courseman"/>
<propertyname="username"value="courseman"/>
<propertyname="password"value="abc123"/>
</bean>
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<!--dataSource属性指定要用到的连接池-->
<propertyname="dataSource"ref="dataSource"/>
<!--configLocation属性指定mybatis的核心配置文件-->
<propertyname="configLocation"value="resources/configuration.xml"/>
</bean>
<!--MapperScannerConfigurer配置-->
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--basePackage指定要扫描的包,在此包之下的映射器都会被
搜索到。可指定多个包,包与包之间用逗号或分号分隔-->
<propertyname="basePackage"value="com.abc.mapper"/>
</bean>
</beans>
TeacherMapper mapper
= (TeacherMapper)ctx.getBean("teacherMapper");
package com.abc.mapper;
import com.abc.domain.Teacher;
import org.springframework.stereotype.Component;
@Component("myTeacherMapper")
publicinterface TeacherMapper {
public Teacher getById(int id);
}
TeacherMapper mapper
= (TeacherMapper)ctx.getBean("myTeacherMapper");
还有一点顺便提及,若映射器接口(如TeacherMapper接口)与相应的映射配置文件(如TeacherMapper.xml)同名且在同一目录下,就无需在核心配置文件configuration.xml中使用mappers元素来指定映射配置文件了。读者可自行实验。