Spring 嵌套方法AOP不生效問題

來源:互聯網
上載者:User

標籤:mic   代碼   嵌套   data   cdata   mes   pre   增強   dynamic   

問題描述, 如下Abc定義為一個Bean, b()方法添加@TargetDatasource,定義切面DynamicDataSourceAspect,期望:調用a()方法,b()方法上的AOP攔截能生效。實際不生效。

@Servicepublic class Abc {public void a(){
b();
}

@TargetDatasource(value=abc)public void b(){
}}

 

AOP代碼:

@Order(-1)@Component@Slf4j@Aspectpublic class DynamicDataSourceAspect {  /**   * set data source value.   */  @Before(value = "@annotation(targetDataSource)", argNames = "targetDataSource")  public void setDataSource(TargetDataSource targetDataSource) {    if (targetDataSource != null && targetDataSource.value() != null) {      log.info("Databse value: {}", targetDataSource.value());      DynamicDataSourceHolder.set(targetDataSource.value());    }  }  /**   * clear data source value.   */  @After(value = "@annotation(targetDataSource)", argNames = "targetDataSource")  public void clearDataSource(TargetDataSource targetDataSource) {    DynamicDataSourceHolder.clear();  }}

 

問題分析:

我們都知道Spring aop有兩種實現方式,基於Interface組建代理程式和cglib組建代理程式。上面的例子中,當調用a()方法時,調用者拿到的是Abc的代理類,即增強類。如果a()方法上有@TargetDatasource註解,攔截會生效。然而,在a()方法裡調用b(),b方法上的攔截不會生效。原因是因為a()調用b(), 用的是b()方法的目標類,而不是代理類,所以攔截不生效。

 

解決方案:

1. 重構代碼, 把b()方法移到一個Bean裡面。

2. 調整a()方法如下:

@Servicepublic class Abc {public void a(){   ((Abc)AopContext.currentProxy()).b();}@TargetDatasource(value=abc)public void b(){}}

 

Sping 官方解釋 - https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#aop 

Spring 嵌套方法AOP不生效問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.