原本事物处理是要配置到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中写上事物处理的代码(本人还没有测试哦 只是思路)