在 Spring 中,bean 被一個代理物件封裝,當從外部物件呼叫時,代理物件的方法也會被呼叫。通過使用這個技巧,事務管理在代理物件的方法中執行。但是,當您在同一個 bean 中呼叫一個方法時,如果您希望被呼叫的方法在另一個事務中與呼叫者方法一起運行,這是不可能的。由于在同一個 bean 中的方法呼叫不會通過執行事務操作的代理物件。為了解決這個問題,提出了 bean 自身內部的自我注入。
像這樣
@Service
public class MyService{
@Autowired
public MyService myService;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void method1(){
method2();// runs in the same transaction with method1
myService.method2();// runs in separate transaction from method1
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void method2(){
}
}
我想問一下自注入是否會導致記憶體泄漏。外部 bean MyService 包括注入的 myService 和 myService 應包括 MyService 型別的屬性,其中應包括 MyService 型別的屬性...。
uj5u.com熱心網友回復:
該服務不是復制的,它只是一個參考。但我會警惕這樣的設計:它會創建一個回圈參考,并且不可能立即創建物件圖。您首先需要創建不完整的服務,然后設定其欄位。此外,發現這種對自我的依賴有點令人困惑和驚訝
我會提出一個不同的解決方案:
@Component
public class WithTransaction {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void requiresNew(final Runnable runnable) {
runnable.run();
}
}
@Service
public class MyService{
private final WithTransaction withTransaction;
@Autowired
public MyService(final WithTransaction withTransaction) {
this.withTransaction = withTransaction;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void method1(){
method2();// runs in the same transaction with method1
withTransaction.requiresNew(this::method2); // runs in separate transaction from method1
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void method2(){
}
}
如果你能避免它:不要從你的服務呼叫服務本身的任何公共方法。將服務拆分為更小的組件,以便每個“公共”呼叫都必須通過代理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/518075.html
標籤:爪哇春天依赖注入交易
