applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/mvc 12 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 13 http://www.springframework.org/schema/aop 14 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 15 http://www.springframework.org/schema/tx 16 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 17 18 <context:property-placeholder location="classpath:jdbc.properties"/> 19 20 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 21 <property name="driverClass" value="${jdbc.driverClass}"></property> 22 <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> 23 <property name="user" value="${jdbc.user}"></property> 24 <property name="password" value="${jdbc.password}"></property> 25 </bean> 26 27 <bean id="testService" class="cn.byref.spring.demo.TestServiceImpl"> 28 <property name="testDao" ref="testDao"></property> 29 </bean> 30 31 <bean id="testDao" class="cn.byref.spring.demo.TestDaoImpl"> 32 <property name="dataSource" ref="dataSource"></property> 33 </bean> 34 35 </beans>
TestDaoImpl.java
package cn.byref.spring.demo; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.support.JdbcDaoSupport; public class TestDaoImpl extends JdbcDaoSupport implements TestDao { @Override public void addAge(String userName, int age) { JdbcTemplate tpl = this.getJdbcTemplate(); String sql = "update test set age = ? where username = ?"; int cnt = tpl.update(sql, new Object[] { age, userName}); System.out.println("effected = " + cnt); } }
TestClass.java
package cn.byref.spring.demo; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.mchange.v2.c3p0.ComboPooledDataSource; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class TestClass { @Resource private ComboPooledDataSource dataSource; @Resource private TestDao testDao; @Resource TestService testService; @Test public void test(){ // testDao.addAge("侠客", 1001); testService.addAge("侠客", 110); } }