@Transaction作用在Controller层或者是service层的配置,解决事务的作用域

一,如果在service层加事务

1.事务一般要放在Service层,放在Controller也可以,。

2.在springmvc的配置文件中扫描controller时要忽略service,因为在springmvc的配置文件加载的service事务不起作用。所以在springmvc.xml中:

         

<!-- 扫描web相关的bean 只扫描@controller,忽略service ,因为springmvc扫描的service没有事务-->

<context:component-scan base-package="com.xxx">

<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />

</context:component-scan>

spring.xml中扫描@service

<!-- 扫描daoservice,因为spring扫描的service才具有事务功能 -->

<context:component-scan base-package="com.xxx">

</context:component-scan>

 3.在service层中的类方法加@Transaction注解即可

    前提是:在spring.xml配置了:

    <!-- 事务配置 -->

     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

 <!-- 使用annotation注解方式配置事务 -->

    <tx:annotation-driven transaction-manager="transactionManager" />

二,在Controller层加事务:

将事物加在contrller层,只需要在springmvc.xml中加上<tx:annotation-driven/>即可,也要在扫描包同service一样(上面)并且contrller类中加上@Transactional即可。

前提是在spring.xml中要有事物管理器的配置即

 

 <!-- 事务配置 -->

     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

注意: Controller层只支持 @Transactional 注解式事务!

注意:@Transaction不起作用的:1.静态(static )方法,  2,(private)私有化方法,   3,自调用方法(因为事务是依赖aop的,而aop是通过动态代理实现的),   

参考:https://blog.csdn.net/tongyu75/article/details/53323892

猜你喜欢

转载自blog.csdn.net/weixin_42533856/article/details/81701781