原本事物處理是要配置到service的,無奈項目是這樣的,來到新公司接手的項目是多個項目用的公共的service,爲了避免在service中不添加不是公用的方法,每一個項目用到的方法都寫在了controller層,如今呢要給一些多表操做的方法添加事物處理,原本是打算把controller層的方法挪到service,可是這樣的公用的service就會會添加不少方法,而另外一個項目就用不到,或者另外一個項目用到的方法這個項目用不到。最終決定 若是事物能加在controller層 就能夠解決如今的問題了。web
具體作法以下 只羅列關鍵配置spring
在spring.xml中配置(就是sprign的配置文件)
<!-- 掃描service、dao -->
<!-- 掃描註解@Component , @Service , @Repository。 要把 controller去除,controller是在spring-servlet.xml中配置的,若是不去除會影響事務管理的。 -->express
<!-- 掃描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的配置文件)mvc
<!-- 註解掃描包 --> <context:component-scan base-package="com.systek.scenic.web.controller"/> <!-- 開啓註解 --> <mvc:annotation-driven/> <!-- 開啓註解 --> <import resource="classpath:spring-tx.xml"/>
在事物處理spring-tx.xml的配置文件中配置app
<?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註解便可 如ide
@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中寫上事物處理的代碼(本人還沒有測試哦 只是思路)