在 Spring MVC 應用開發中,Service 層是業務邏輯的核心,而事務管理則是保證數據一致性的關鍵。本文將詳細介紹如何在 Spring 容器中配置 Service、定義接口與實現類,並實現聲明式事務控制。
首先定義商品查詢的 Service 接口:
public interface ItemsService {
// 商品查詢列表
List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}
接著實現該接口,注入自定義 Mapper 進行數據查詢:
public class ItemsServiceImpl implements ItemsService {
@Autowired
private ItemsMapperCustom itemsMapperCustom;
@Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
}
在 resources/spring 目錄下創建 applicationContext-service.xml,將 Service 實現類註冊為 Bean:
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<!-- 商品管理的 Service -->
<bean id="itemsService" class="com.iot.learnssm.firstssm.service.impl.ItemsServiceImpl"></bean>
</beans>
在 resources/spring 下創建 applicationContext-transaction.xml,配置事務管理器、通知與 AOP 切面:
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:aop="https://www.springframework.org/schema/aop"
xmlns:tx="https://www.springframework.org/schema/tx"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx-4.0.xsd
https://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 事務管理器:針對 MyBatis 操作數據庫,使用 JDBC 事務控制 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 事務通知:定義傳播行為 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- AOP 配置:將事務通知織入 Service 層 -->
<aop:config>
<aop:pointcut id="servicePointcut" expression="execution(* com.iot.learnssm.firstssm.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>
</aop:config>
</beans>
透過上述配置,Spring 將自動管理 Service 的事務邊界,增刪改操作採用 REQUIRED 傳播行為,查詢操作則設為 SUPPORTS 唯讀,既保證了數據一致性,又提升了查詢性能。