Overridepublic void test1 MaterialQuestionnaire materialQuestionnaire=new MaterialQuestionnaire; materialQuestionnairesetUpAtLocalDateTimenow; materialQuestionnairesetMaterialIdt1; materi
要让test2方法的事务生效,可以在调用test2方法的地方添加一个代理对象,通过代理对象来调用test2方法。
首先,需要在类中注入一个代理对象来调用test2方法。可以使用Spring的AOP功能来实现代理。在类上添加注解@EnableAspectJAutoProxy来启用Spring的AOP功能。
然后,创建一个切面类,在切面类中定义一个使用@Transactional注解的方法,该方法会在调用test2方法之前执行。在该方法中使用TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()来设置事务回滚。
最后,在调用test2方法的地方,通过代理对象来调用该方法。
以下是修改后的代码示例:
import org.springframework.aop.framework.AopContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
@Component
@EnableAspectJAutoProxy
public class MyClass {
public void test1() {
MaterialQuestionnaire materialQuestionnaire = new MaterialQuestionnaire();
materialQuestionnaire.setUpAt(LocalDateTime.now());
materialQuestionnaire.setMaterialId("t1");
materialQuestionnaire.setDescription("测试");
this.save(materialQuestionnaire);
((MyClass)AopContext.currentProxy()).test2();
}
@Transactional
public void test2() {
MaterialQuestionnaire materialQuestionnaire = new MaterialQuestionnaire();
materialQuestionnaire.setUpAt(LocalDateTime.now());
materialQuestionnaire.setMaterialId("t2");
materialQuestionnaire.setDescription("测试");
this.save(materialQuestionnaire);
int a = 1 / 0;
}
private void save(MaterialQuestionnaire materialQuestionnaire) {
// 保存逻辑
}
}
注意:为了让AopContext.currentProxy()方法生效,需要在Spring配置文件中添加<aop:aspectj-autoproxy proxy-target-class="true"/>来开启CGLIB代理
原文地址: https://www.cveoy.top/t/topic/iG6R 著作权归作者所有。请勿转载和采集!