当前位置: 首页 > 后端技术 > Java

SpringBoot如果服务@Transactional的方法不是公共的会发生什么?(2)

时间:2023-04-01 15:27:15 Java

bySpringBoot如果一个服务的方法@Transactional不是public会怎样?我们可以知道,当一个servie中@Transactional修饰的所有方法都是no-public时,Spring是不会创建代理类的,也就是我们的transaction不能生效~。如果@Transactional修饰的方法有no-public和public怎么办?在这种情况下,spring也会创建代理类。那么问题来了,如果这个public方法调用了一个no-public方法怎么办?有两种情况:1、这个no-public方法上有一个帽子(@Transactional);2.这个no-public方法没有帽子;下面详细分析:图1finalvoidtestSaveAd(){try{MethodInterceptorvar10000=this.CGLIB$CALLBACK_0;如果(var10000==null){CGLIB$BIND_CALLBACKS(this);var10000=this.CGLIB$CALLBACK_0;}if(var10000!=null){var10000.intercept(this,CGLIB$testSaveAd$0$Method,CGLIB$emptyArgs,CGLIB$testSaveAd$0$Proxy);}else{super.testSaveAd();}}catch(Error|RuntimeExceptionvar1){throwvar1;}catch(Throwablevar2){thrownewUndeclaredThrowableException(var2);}}publicfinalvoidtestSaveAd2(){try{MethodInterceptorvar10000=this.CGLIB$CALLBACK_0;如果(var10000==null){CGLIB$BIND_CALLBACKS(this);var10000=this.CGLIB$CALLBACK_0;}if(var10000!=null){var10000.intercept(this,CGLIB$testSaveAd2$1$Method,CGLIB$emptyArgs,CGLIB$testSaveAd2$1$Proxy);}else{super.testSaveAd2();}}catch(Error|RuntimeExceptionvar1){throwvar1;}catch(Throwablevar2){thrownewUndeclaredThrowableException(var2);}}finalvoidsave(){try{MethodInterceptorvar10000=this.CGLIB$CALLBACK_0;如果(var10000==null){CGLIB$BIND_CALLBACKS(this);var10000=this.CGLIB$CALLBACK_0;}if(var10000!=null){var10000.intercept(this,CGLIB$save$2$Method,CGLIB$emptyArgs,CGLIB$save$2$Proxy);}else{super.save();}}catch(Error|RuntimeExceptionvar1){throwvar1;}猫ch(Throwablevar2){thrownewUndeclaredThrowableException(var2);}}上面三段代码分别是agent类强化了我们定义的三个方法的情况;@SpringBootTest@RunWith(SpringRunner.class)publicclassTransactionTest{@AutowiredprivateTransactionServiceTesttransactionServiceTest;@TestpublicvoidtansTest(){transactionServiceTest.testSaveAd2();}}运行上面的测试用例,控制台没有输出commit字样,换个测试姿势:importjava.lang.reflect。方法;@Slf4j@SpringBootTest@RunWith(SpringRunner.class)publicclassTransactionTest{@AutowiredprivateTransactionServiceTesttransactionServiceTest;@Transactional(rollbackFor=Exception.class)@TestpublicvoidtansTest2()throwsException{invokeMethod(transactionServiceTest,"testSaveAd"null,null);}publicstaticObjectinvokeMethod(Objectowner,StringmethodName,Class[]argsClass,Object[]args)throwsException{ObjectobjRtn=null;类ownerClass=owner.getClass();方法method=ownerClass.getDeclaredMethod(methodName,null);//方法method=ownerClass.getMethod(methodName,argsClass);方法.setAccessible(true);方法调用(所有者,参数);}}以下是Log输出:TransactionsynchronizationcommittingSqlSession[org.apache.ibatis.session.defaults.DefaultSqlSession@6904f5a0]哦,没有有一个眼花缭乱的“commit”这是为什么呢?见图2,TransactionServiceTest实例不是代理类,所以交易无效!

猜你喜欢