接上篇配置,在com.test.spring.tx包下加入業務接口和類
####業務接口類spring
public interface BookShopService { public void purchase(int userId,int bookId); }
####業務實現類,注意添加有事務app
package com.test.spring.tx; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service("bookShopService") public class BookShopServiceImpl implements BookShopService{ @Autowired private BookShopDao bookShopDao; //聲明式事務 @Transactional @Override public void purchase(int userId, int bookId) { //1.獲取書的單價 double price = bookShopDao.getBookPriceByBookId(bookId); //2.更新書的數量 bookShopDao.updateBookStock(bookId); //3.更新用戶餘額 bookShopDao.updateUserBalance(userId, price); } }
####測試類ide
package com.test.spring.tx; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestTx { private ApplicationContext ctx; private BookShopService bookShopService; { ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); bookShopService = ctx.getBean(BookShopService.class); } @Test public void testBookService(){ bookShopService.purchase(1000, 1001); } }
####配置文件測試
<context:component-scan base-package="com.test.spring.tx"></context:component-scan> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置數據源 --> <bean id="dataSources" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSources"></property> </bean> <!-- 配置事物管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSources"></property> </bean> <!-- 啓用事物註解 --> <tx:annotation-driven transaction-manager="transactionManager"/>