@Transactional self-invocation (in effect, a method within the target object calling another method
·
IDEA提示信息
@Transactional self-invocation (in effect, a method within the target object calling another method of the target object) does not lead to an actual transaction at runtime
代码示例
@Service
public class TransactionalDemo {
@Transactional
public void aaa() {
System.out.println("调用a方法");
}
public void bbb() {
System.out.println("调用b方法");
aaa();
}
}
写完这个代码之后,可以看到aaa()方法下有黄色的波浪线,将鼠标放上去提示开始的信息。警告我们这样使用@Transactional注解是不会生效的。
原因
Spring的事务是通过AOP来实现的,只有通过代理对象调用@Transactional注解的对象方法时,事务才会生效,也就是直接调用aaa()方法事务才会生效,调用bbb()方法后间接调用aaa()方法事务是不会生效的。因为这次调用并不是通过代理对象来实现的。
解决方案
可以将aaa()方法重新写到一个类中,然后在bbb()方法中调用
@Service
public class AAADemo {
@Transactional
public void aaa() {
System.out.println("调用a方法");
}
}
@Service
public class TransactionalDemo {
@Autowired
private AAADemo aaaDemo;
public void bbb() {
System.out.println("调用b方法");
aaaDemo.aaa();
}
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐


所有评论(0)