SSM对于事务的管理,基于注解

spring配置文件:

<!--不扫描controller-->
context:component-scan
		base-package="com.xx">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:exclude-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>

SpringMVC配置文件:

<!-- 自动扫描该包,SpringMVC只扫描controllerr -->
<context:component-scan
		base-package="com.xx.controller">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
		<context:include-filter type="annotation"
			expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>

Spring-Mybatis配置文件:

<!-- 配置事务管理器 -->
<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置基于注解的声明式事务 @Transactional -->
<!--proxy-target-class="true"表示支持CGLB代理,如果不加,只支持JDK的代理,默认只支持面向接口,也就是说放在实现类上,事务不生效-->
<tx:annotation-driven
	transaction-manager="transactionManager" proxy-target-class="true" />

 

为什么要分开配置spring 和 SpringMVC的扫描?

 

因为spring的context是父子容器,ContextLoaderListener监听器加载spring配置文件,

产生的是父容器,mvc加载mvc的配置文件,产生了子容器,子容器对@Controller进行装配扫描时,

也装配了@Service注解的实例,因为在@Contoller实例依赖@Service实例,而@Service注解的实例,

也就是一般的事务控制层,应该是有父容器初始化,以保证事务的增强处理,否则会事务事务处理能力。

 

XxserviceImpl:

        //在catch中有两种处理方法,1.抛出去异常,让controllerAdvice处理.
        //2.手动回滚,下面例子为手动回滚
        //该注解可配置在类,方法上。作用域public
    @Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteLineAndTowerById(String id) {
		try {
			aaMapper.deleteById(id);
			int i = 5 / 0;
			bbMapper.deleteById(id);
		} catch (Exception e) {
			log.error("错误信息:" + e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
	}

注意:InnoDB引擎支持事务,在my.ini中的【mysqlId】下添加default-storage-engine=INNODB

具体的事务类型在public enum Propagation 枚举中,默认为Required

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章