本來事物處理是要配置到service的,無奈項目是這樣的,來到新公司接手的項目是多個項目用的公共的service,為了不在service中不添加不是公用的方法,每個項目用到的方法都寫在了controller層,現在呢要給一些多表操作的方法添加事物處理,本來是打算把controller層的方法挪到service,但是這樣的公用的service就會會添加很多方法,而另一個項目就用不到,或者另一個項目用到的方法這個項目用不到。最終決定 如果事物能加在controller層 就可以解決現在的問題了。
具體做法如下 只羅列關鍵配置
在spring.xml中配置(就是sprign的配置文件)
<!-- 掃描service、dao -->
<!-- 掃描注解@Component , @Service , @Repository。 要把 controller去除,controller是在spring-servlet.xml中配置的,如果不去除會影響事務管理的。 -->
<!-- 掃描service、dao -->
<!-- 掃描注解@Component , @Service , @Repository。 要把 controller去除,controller是在spring-servlet.xml中配置的,如果不去除會影響事務管理的。 -->
<context:component-scan base-package="com.systek.scenic"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
<!-- 或者如下寫法也行 include是包含 exclude是排除 任意注釋掉一個或者都不注釋都可以的-->
<!--<context:component-scan base-package="com.systek.scenic">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>-->
在mvc.xml中配置(就是spring Mvc的配置文件)
<!-- 注解掃描包 --> <context:component-scan base-package="com.systek.scenic.web.controller"/> <!-- 開啟注解 --> <mvc:annotation-driven/> <!-- 開啟注解 --> <import resource="classpath:spring-tx.xml"/>
在事物處理spring-tx.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 事務配置 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dbPool" /> </bean> <!-- 使用annotation注解方式配置事務 --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
然后在>controller層中對應的方法上加上@Transactional注解即可 如
@RequestMapping(value = "/Save", method = RequestMethod.POST)
@ResponseBody
//@Transactional(rollbackFor = { Exception.class })
@Transactional
public Result save(HttpServletRequest request, GuiderRentVO guiderRentVO, Model model)
{
//......
}
經測試注解@Transactional寫在controller是管用的 寫在service是不管用的,因為我們的事務處理代碼寫在了mvc.xml中
如果需要在service也支持 可以嘗試在spring.xml中寫上事物處理的代碼(本人尚未測試哦 只是思路)
