一,如果在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:
<!-- 扫描dao和service,因为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是通过动态代理实现的),