事务在系统服务启动的时候就加载了,一般的,我们把事务配在service层,利用service的业务逻辑借口统一的管理。为什么不用在dao层呢?因为一个service有可能调用多个dao,而这多个dao有可能相互联系,有时候一个操作需要调用多次数据库,但是这多次调用要么全提交,要么全回滚。因此,在dao层调用事务理论上说不是一个很明智的选择。应该有业务逻辑层service层负责事务,统一处理。具体事务配置的代码如下:
<!-- Transaction template for Managers -->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="transactionAttributes">
<props>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
其中update*表示service层中的方法以update开头的所有方法,没有readOnly标示的标识该操作可以修改数据库,否则该方法不能操作数据库,只能进行类似查询的功能。最后一个*代表除了以上所有的方法外的其它方法。
这个调用事务的类是一个抽象类,因此在自己具体实现的类里面如果需要配置事务,只要声明一下就可以了。另外,也可以覆盖该方法,修改属于自己业务模块的方法名的读写数据库的操作权。具体代码如下:
<bean id="fileManager" parent="txProxyTemplate">
<property name="target">
<bean class="com.mycore.filemanager.service.impl.FileManagerImpl" autowire="byName">
</bean>
</property>
<property name="transactionAttributes">
<props>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
这样就配置ok了,在自己的实现类里面如果企图在不能修改数据库的方法里面修改数据库,spring会报出该方法是只读的一个异常。
关于Spring 事务配置
最新推荐文章于 2021-11-05 10:55:27 发布