1、applicationContext.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: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 http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 配置数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="maxActive" value="10"></property>
<property name="maxIdle" value="5"></property>
</bean>
<!-- SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
</bean>
<!--
<!-- 配置mapper -->
<!--spring和mybatis整合包中的MapperFactoryBean负责生成mapper代理对象-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-代理的接口-->
<property name="mapperInterface" value="sjzc.gong.xiao.mapper.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>-->
<!--由于使用上面这种方法配置mapper的话,对于每个接口都需要配置一遍,比较繁琐,可以使用扫描器-->
<!-- MapperScannerConfigurer:mapper的扫描器,对包下边的接口自动生成代理对象,自动创建到spring容器中 ,bean的id就是mapper类的类名(首字母小写)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="sjzc.gong.xiao.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
2、测试
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
User user=userMapper.findUserById(1);
System.out.println(user);
}
}