线程Thread中声明式事务不起作用

本文介绍了一种通过编程方式实现的事务处理方法,该方法利用Spring框架提供的Transaction API来手动控制事务的开启、提交和回滚过程。具体实现中,通过DefaultTransactionDefinition设置事务传播行为,并借助PlatformTransactionManager进行事务管理。

原因:未知

解决方案: 使用编程式事务

	@Override
								public void run() {
									DefaultTransactionDefinition def = new DefaultTransactionDefinition();
									def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
									PlatformTransactionManager txManager = ContextLoader.getCurrentWebApplicationContext().getBean(PlatformTransactionManager.class);
									TransactionStatus status = txManager.getTransaction(def);
									try {
	                                                                        testDao.save(entity);
										txManager.commit(status); // 提交事务
									} catch (Exception e) {
										System.out.println("异常信息:" + e.toString());
										 txManager.rollback(status); // 回滚事务
									}
								
								}

使用`new Thread`开启线程后,线程内方法会脱离Spring声明式事务管理。Spring的声明式事务是基于AOP和线程绑定机制实现的,它会将事务信息与当前线程进行绑定。当使用`new Thread`创建新线程时,新线程与原线程是不同的执行上下文,原线程绑定的事务信息不会传递到新线程中,因此新线程内的方法无法参与到原线程事务中,即脱离了Spring声明式事务的管理范围。 例如在引用[1]中提到,在`new Thread`的`run`方法里,Spring无法处理该线程事务声明式事务无效。需要手动创建`DefaultTransactionDefinition`对象,获取`PlatformTransactionManager`,并手动开启、提交或回滚事务,这也侧面说明了`new Thread`开启的线程内方法脱离了Spring声明式事务管理,需要手动管理事务: ```java new Thread(new Runnable() { @Override public void run() { // spring无法处理thread事务声明式事务无效 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); PlatformTransactionManager txManager = ContextLoader.getCurrentWebApplicationContext().getBean(PlatformTransactionManager.class); TransactionStatus status = txManager.getTransaction(def); try { processEachPlan(learn); txManager.commit(status); // 提交事务 } catch (Exception e) { Logger.info("异常信息:" + e.toString()); txManager.rollback(status); // 回滚事务 } } }).start(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值