一般都会在Services层使用事务,但是可不可以在Controller层使用呢,经过查询资料与实验,证明是可以在Controller层使用事务的。
1、在applicationContext.xml中添加如下配置:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="datasource"></property> </bean>
2、在servlet.xml中添加如下配置:
<context:component-scan base-package="com.mytemplate.controller"> <!--在对controller的包进行扫描时,添加如下配置,就可以支持在Controller上面加事务--> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--指定事务的管理器--> <tx:annotation-driven transaction-manager="transactionManager"/>然后,就可以在Controller的类上或者控制器的方法上使用注解@Transactional来标记该类或者该方法使用了事务。