配置spring.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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/context
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 引入jdbc配置文件 -->
<context:property-placeholder location="jdbc.properties"/>
<!-- 创建jdbc数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 创建SqlSessionFactory,同时指定数据源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="mybatis-config.xml"/>
</bean>
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<!-- 定义UserDao -->
<bean id="userDao" class="org.zsm.study.mybatis.dao.impl.UserDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>
</beans>
测试:
package test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.zsm.study.mybatis.dao.IUserDao;
import org.zsm.study.mybatis.domain.User;
public class TestUseDao {
private ApplicationContext ctx = null;
@Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@After
public void tearDown() throws Exception {
ctx = null;
}
@Test
public void add() {
User user = new User();
user.setUserName("有为");
user.setUserAge("21");
user.setUserAddress("hubei huanggang");
IUserDao userDao = (IUserDao) ctx.getBean("userDao");
userDao.Save(user);
}
}