Spring事务的两种方式

1.适合中小型项目

第一:在pom.xml中添加:

<!-- spring 依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- Spring事务用到的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>

第二:在applicationContext.xml文件里面添加:
<!--使用spring的事务处理-->
<!--1.声明事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--连接数据库,指定数据源-->
<property name="dataSource" ref="MyDataSource"></property>
</bean>
<!--2.开启事务注解驱动,告诉spring使用注解管理事务,创建代理对象;适合中小型项目-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
第三:最后在主方法上增加@Transactional

 

==========================================================================================================================================================

==========================================================================================================================================================

2.适合大型项目的事务,只有以下两个步骤

 第一,在在pom.xml中添加:

<!-- aspectj 依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
第二:在applicationContext.xml文件里面添加:
<!--声明式事务处理,和源代码完全分离-->
<!--1.声明事务管理对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="MyDataSource"></property>
</bean>
<!--2.声明业务方法的事务属性(隔离级别、传播行为、超时时间)
id是自定义名称,表示配置内容
transaction-manager:事务管理器对象的ID-->
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--tx:method:给具体的方法配置事务属性,method可以有多个,给不同的方法配置事务属性
name:方法名,1)完整的方法名,不带包和类;2)可以使用通配符*,表示任意字符
propagation:传播行为,枚举值
isolation:隔离级别
rollback-for:指定的异常类名,全限定类名,发生异常,一定回滚
-->
<tx:method name="buy" isolation="DEFAULT" propagation="REQUIRED"
rollback-for="java.lang.NullPointerException,com.ykh.excep.NotEnoughException"/>

<!--使用通配符,指定很多方法-->
<!--指定新增方法-->
<tx:method name="add*" propagation="REQUIRES_NEW"></tx:method>
<!--指定修改方法-->
<tx:method name="modify*"></tx:method>
<!--指定删除方法-->
<tx:method name="remove*"></tx:method>
<!--查询方法,querysearchfind方法等-->
<tx:method name="*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>

<aop:config>
<!--3.配置切入点表达式,指定哪些包里面的哪些类需要使用事务
id:切入点表达式的名称,唯一值
expression:切入点表达式,指定哪些包哪些类哪些方法要使用事务,aspectj会创建代理对象-->
<aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/>

<!--配置增强器:关联advicepointcut
advice-ref:通知,上面的tx:advice的配置
pointcut-ref:切入点表达式的id
-->
<aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"></aop:advisor>
</aop:config>


posted @ 2020-11-22 14:03  小寒2020  阅读(550)  评论(0编辑  收藏  举报