標籤: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不生效問題