spring mvc 给Controller添加事务

来源:互联网 发布:webrtc 源码介绍 编辑:程序博客网 时间:2024/06/05 21:06

首先扫描配置要对:

   原理:因为spring容器和spring-mvc是父子容器,spring容器会先加载,如果此时扫描了Controller,但未扫描到Service。
spring事务配置文件还有上下文都是通过org.springframework.web.context.ContextLoaderListener加载的,而spring MVC的action是通过org.springframework.web.servlet.DispatcherServlet加载的 。
web是先启动ContextLoaderListener后启动DispatcherServlet 在ContextLoaderListener加载的时候Controller并没在容器中,所以现在使用AOP添加事务或者扫描注解都是无用的。

结论:让spring扫描注册Service实现类,让MVC扫描注册Controller,此时spring父容器已经注册Service为Bean,此时事务可以得到正常配置。


扫描配置如下:
spring-context.xml

<context:component-scan base-package="com.freecg.green007">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

spring-mvc.xml

<context:component-scan base-package="com.freecg.green007"> 
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

spring父容器不扫描@Controller,MVC子容器不扫描@Service.

事务配置如下:
spring-context.xml

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
------------------------------------------------------------------------------------------------------------------------------------------------------------------


    一般而言,事务都是加在Service层的,也可以加在Controller层

    在spring-framework-reference.pdf文档中有这样一段话:

<tx:annotation-driven/>

only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put

<tx:annotation-driven/>

in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. 

    这句话的意思是,<tx:annoation-driven/>只会查找和它在相同的应用上下文件中定义的bean上面的@Transactional注解,如果你把它放在Dispatcher的应用上下文中,它只检查控制器上的@Transactional注解,而不是你services上的@Transactional注解。

    于是,我将事务配置定义在Spring MVC的应用上下文(spring-mvc.xml)中,

命名空间加红色部分

xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                 http://www.springframework.org/schema/tx                 http://www.springframework.org/schema/tx/spring-tx.xsd

spring-mvc.xml加<tx:annotation-driven/>

@Transactional(rollbackFor = { Exception.class})注解打在Controller上,

事务起就可以作用。

    综上,在Spring MVC中,事务不仅可以加在Service层,同样也可以加在Controller层


参考:http://5880861.blog.51cto.com/5870861/1544168

           http://blog.csdn.net/suyu_yuan/article/details/61190503


原创粉丝点击