@Transactional 注解失效的3种原因及解决办法
Java后端技术
共 10670字,需浏览 22分钟
·
2022-04-20 20:27
1、初看一脸懵逼,看懂直接跪下! 2、再见 BeanUtils!性能真拉跨! 3、被公司辞退拿了22万补偿金,原东家称回来后每月涨薪7000,只要退还22万 4、用 Dubbo 传输文件?被老板一顿揍! 5、45 个 Git 经典操作场景,专治不会合代码!
Transactional失效场景介绍
@Transactional
注解将会不起作用。例如以下代码。@Transactional
标注实现,修饰一个默认访问符的方法/**
* @author zhoujy
**/
@Component
public class TestServiceImpl {
@Resource
TestMapper testMapper;
@Transactional
void insertTestWrongModifier() {
int re = testMapper.insert(new Test(10,20,30));
if (re > 0) {
throw new NeedToInterceptException("need intercept");
}
testMapper.insert(new Test(210,20,30));
}
}
@Component
public class InvokcationService {
@Resource
private TestServiceImpl testService;
public void invokeInsertTestWrongModifier(){
//调用@Transactional标注的默认访问符方法
testService.insertTestWrongModifier();
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Resource
InvokcationService invokcationService;
@Test
public void testInvoke(){
invokcationService.invokeInsertTestWrongModifier();
}
}
testMapper.insert(new Test(10,20,30));
操作不会进行回滚。如果TestServiceImpl#insertTestWrongModifier
方法改为public的话将会正常开启事务,testMapper.insert(new Test(10,20,30));
将会进行回滚。第二种
@Transactional
标注的方法。这种情况下也会导致事务不开启。示例代码如下。/**
* @author zhoujy
**/
@Component
public class TestServiceImpl implements TestService {
@Resource
TestMapper testMapper;
@Transactional
public void insertTestInnerInvoke() {
//正常public修饰符的事务方法
int re = testMapper.insert(new Test(10,20,30));
if (re > 0) {
throw new NeedToInterceptException("need intercept");
}
testMapper.insert(new Test(210,20,30));
}
public void testInnerInvoke(){
//类内部调用@Transactional标注的方法。
insertTestInnerInvoke();
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Resource
TestServiceImpl testService;
/**
* 测试内部调用@Transactional标注方法
*/
@Test
public void testInnerInvoke(){
//测试外部调用事务方法是否正常
//testService.insertTestInnerInvoke();
//测试内部调用事务方法是否正常
testService.testInnerInvoke();
}
}
testMapper.insert(new Test(10,20,30))
操作将会被回滚;@Transactional
标注的事务方法,运行结果是事务不会正常开启,testMapper.insert(new Test(10,20,30))
操作将会保存到数据库不会进行回滚。第三种
/**
* @author zhoujy
**/
@Component
public class TestServiceImpl implements TestService {
@Resource
TestMapper testMapper;
@Transactional
public void insertTestCatchException() {
try {
int re = testMapper.insert(new Test(10,20,30));
if (re > 0) {
//运行期间抛异常
throw new NeedToInterceptException("need intercept");
}
testMapper.insert(new Test(210,20,30));
}catch (Exception e){
System.out.println("i catch exception");
}
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Resource
TestServiceImpl testService;
@Test
public void testCatchException(){
testService.insertTestCatchException();
}
}
testMapper.insert(new Test(210,20,30))
操作并没有回滚。@Transactional
注解不起作用,@Transactional
注解失效的主要原因。下面结合spring中对于@Transactional
的注解实现源码分析为何导致@Transactional
注解不起作用。@Transactional注解不起作用原理分析
第一种
@Transactional
注解标注方法修饰符为非public时,@Transactional
注解将会不起作用。这里分析 的原因是,@Transactional
是基于动态代理实现的,@Transactional
注解实现原理中分析了实现方法,在bean初始化过程中,对含有@Transactional
标注的bean实例创建代理对象,这里就存在一个spring扫描@Transactional
注解信息的过程,不幸的是源码中体现,标注@Transactional
的方法如果修饰符不是public,那么就默认方法的@Transactional
信息为空,那么将不会对bean进行代理对象创建或者不会对方法进行代理调用@Transactional
注解实现原理中,介绍了如何判定一个bean是否创建代理对象,大概逻辑是。根据spring创建好一个aop切点BeanFactoryTransactionAttributeSourceAdvisor
实例,遍历当前bean的class的方法对象,判断方法上面的注解信息是否包含@Transactional
,如果bean任何一个方法包含@Transactional
注解信息,那么就是适配这个BeanFactoryTransactionAttributeSourceAdvisor
切点。则需要创建代理对象,然后代理逻辑为我们管理事务开闭逻辑。Transactional
信息,如果有,就表示切点BeanFactoryTransactionAttributeSourceAdvisor
能够应用(canApply)到bean中,AopUtils#canApply(org.springframework.aop.Pointcut, java.lang.Class>, boolean)
public static boolean canApply(Pointcut pc, Class> targetClass, boolean hasIntroductions) {
Assert.notNull(pc, "Pointcut must not be null");
if (!pc.getClassFilter().matches(targetClass)) {
return false;
}
MethodMatcher methodMatcher = pc.getMethodMatcher();
if (methodMatcher == MethodMatcher.TRUE) {
// No need to iterate the methods if we're matching any method anyway...
return true;
}
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
}
//遍历class的方法对象
Set> classes = new LinkedHashSet >(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
classes.add(targetClass);
for (Class> clazz : classes) {
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
for (Method method : methods) {
if ((introductionAwareMethodMatcher != null &&
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
//适配查询方法上的@Transactional注解信息
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}
AbstractFallbackTransactionAttributeSource#getTransactionAttribute
AbstractFallbackTransactionAttributeSource#computeTransactionAttribute
protected TransactionAttribute computeTransactionAttribute(Method method, Class> targetClass) {
// Don't allow no-public methods as required.
//非public 方法,返回@Transactional信息一律是null
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
//后面省略.......
}
不创建代理对象
不进行代理调用
@Transactional
注解标注,但是一个有public修饰符一个没有,那么这种情况我们可以预见的话,一定会创建代理对象,因为至少有一个public修饰符的@Transactional
注解标注方法。insertTestWrongModifier
就会开启事务吗?答案是不会。/**
* @author zhoujy
**/
@Component
public class TestServiceImpl implements TestService {
@Resource
TestMapper testMapper;
@Override
@Transactional
public void insertTest() {
int re = testMapper.insert(new Test(10,20,30));
if (re > 0) {
throw new NeedToInterceptException("need intercept");
}
testMapper.insert(new Test(210,20,30));
}
@Transactional
void insertTestWrongModifier() {
int re = testMapper.insert(new Test(10,20,30));
if (re > 0) {
throw new NeedToInterceptException("need intercept");
}
testMapper.insert(new Test(210,20,30));
}
}
CglibAopProxy.DynamicAdvisedInterceptor#intercept
,有一个逻辑如下,目的是获取当前被代理对象的当前需要执行的method适配的aop逻辑。List
AbstractFallbackTransactionAttributeSource#getTransactionAttribute
AbstractFallbackTransactionAttributeSource#computeTransactionAttribute
@Transactional
注解信息,没有的话就不执行代理@Transactional
对应的代理逻辑,直接执行方法。没有了@Transactional
注解代理逻辑,就无法开启事务,这也是上一篇已经讲到的。第二种
@Transactional
标注的方法。这种情况下也会导致事务不开启。既然事务管理是基于动态代理对象的代理逻辑实现的,那么如果在类内部调用类内部的事务方法,这个调用事务方法的过程并不是通过代理对象来调用的,而是直接通过this对象来调用方法,绕过的代理对象,肯定就是没有代理逻辑了。
/**
* @author zhoujy
**/
@Component
public class TestServiceImpl implements TestService {
@Resource
TestMapper testMapper;
@Resource
TestServiceImpl testServiceImpl;
@Transactional
public void insertTestInnerInvoke() {
int re = testMapper.insert(new Test(10,20,30));
if (re > 0) {
throw new NeedToInterceptException("need intercept");
}
testMapper.insert(new Test(210,20,30));
}
public void testInnerInvoke(){
//内部调用事务方法
testServiceImpl.insertTestInnerInvoke();
}
}
第三种
TransactionAspectSupport#invokeWithinTransaction
protected Object invokeWithinTransaction(Method method, Class> targetClass, final InvocationCallback invocation)
throws Throwable {
// If the transaction attribute is null, the method is non-transactional.
final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
final PlatformTransactionManager tm = determineTransactionManager(txAttr);
final String joinpointIdentification = methodIdentification(method, targetClass);
if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
// Standard transaction demarcation with getTransaction and commit/rollback calls.
//开启事务
TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
Object retVal = null;
try {
// This is an around advice: Invoke the next interceptor in the chain.
// This will normally result in a target object being invoked.
//反射调用业务方法
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// target invocation exception
//异常时,在catch逻辑中回滚事务
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
cleanupTransactionInfo(txInfo);
}
//提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
}
else {
//....................
}
}
来源:blog.csdn.net/qq_20597727/article/
details/84900994
往期热门文章:
1、我滴个乖乖,我复现了Spring的漏洞,害怕! 2、分布式锁用 Redis 还是 Zookeeper? 3、最适合晚上睡不着看的 8 个网站,建议收藏哦 4、String长度有限制吗? 5、14家互联网公司裁员(1-2月裁员清单) 6、Redis实现分布式锁的8大坑!切记! 7、请立即卸载这款 IDEA 插件! 8、Thread.sleep(0) 到底有什么用? 9、为什么不建议用try catch处理异常? 10、MySQL 为啥不能用 UUID 做主键?
评论