spring aop 內部方法調用事務不生效問題解決


方法1:

基於 proxy 的 spring aop 帶來的內部調用問題可以使用 AopContext.currentProxy() 強轉為當前的再調用就可以解決了

例如:


錯誤用法:
public Account getAccountByName2(String userName) {
  return this.getAccountByName(userName);
}


修改為:

public Account getAccountByName2(String userName) {
  return ((AccountService)AopContext.currentProxy()).getAccountByName(userName);
}

 

另外注意:要設置aop實體暴露出來。在springboot的application.java里面加上@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)

 

 

方法2:

  利用初始化方法在目標對象中注入代理對象

在目標對象類中注入spring上下文,通過context獲取代理對象,並調用代理對象的方法。

注意:該方案對於scope為prototype的bean無法適用,因為每次獲取bean時都返回一個新的對象。

  方法2.1:

  //延遲加載方式
private TestService testService;

@Autowired
@Lazy
public void setTestService(TestService testService) {
this.testService = testService;
}


   方法2.2:

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import com.blog.common.aop.service.TestService;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private ApplicationContext context;

    private TestService proxyObject;

    @PostConstruct
    // 初始化方法,在IOC注入完成后會執行該方法
    private void setSelf() {
        // 從spring上下文獲取代理對象(直接通過proxyObject=this是不對的,this是目標對象)
        // 此種方法不適合於prototype Bean,因為每次getBean返回一個新的Bean
        proxyObject = context.getBean(TestService.class);
    }

    public void methodA() throws Exception {
        System.out.println("method A run");
        System.out.println("method A 中調用method B,通過注入的代理對象,調用代理對象的方法,解決內部調用實現的問題。");
        proxyObject.methodB(); //調用代理對象的方法,解決內部調用失效的問題
    }

    public void methodB() {
        System.out.println("method B run");
    }


}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM