我是靠谱客的博主 活泼芹菜,这篇文章主要介绍Spring AOP对嵌套方法不起作用的解决,现在分享给大家,希望可以做个参考。

Spring AOP对嵌套方法不起作用

今天在调研系统操作记录日志时,好多教程都是借助于Spring AOP机制来实现。于是也采用这种方法来实现。在Service中的删除日志方法上注解自定义的切点,但是执行没有生效。

代码如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//尝试删除溢出日志     public synchronized void tryDelOverflowLog() {         logNum++;         if (logNum - LogConst.MAX_NUM > 0) {             int delNum = logNum - LogConst.MAX_NUM + LogConst.EXTRA_NUM;             logNum -= delNum;             removeOverflowLog(delNum);         }     }       //日志溢出后,删除最新入库的日志     @ServiceLog(type = LogConst.TYPE_LOG_RECORD, description = "操作日志缓存区溢出,系统自动清空缓存区")     public void removeOverflowLog(int delNum) {         custLogMapper.removeOverflowLog(delNum);     }

在使用 Spring AOP 的时候,我们从 IOC 容器中获取的 Service Bean 对象其实都是代理对象,而不是那些 Service Bean 对象本身,也就是说获取的并不是被代理对象或代理目标。当我在自己的 Service 类中使用 this 关键字嵌套调用同类中的其他方法时,由于 this 关键字引用的并不是该 Service Bean 对象的代理对象,而是其本身,故 Spring AOP 是不能拦截到这些被嵌套调用的方法的。

要解决这个问题

最简单的方法是把自身注入到自身,用注入的这个自身去调用本方法。或者你也可以不用spring aop而是用aspectj weaving,倒是可以测底的解决该问题。我采用的是把自身注入到自身中。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    /**      * 通过注入自身解决,Spring AOP嵌套调用不生效的问题      */     @Autowired     private ApplicationContext applicationContext;     private LogService self;     @PostConstruct     private void init() {         self = (LogService) applicationContext.getBean("logService");     }    //尝试删除溢出日志     public synchronized void tryDelOverflowLog() {         logNum++;         if (logNum - LogConst.MAX_NUM > 0) {             int delNum = logNum - LogConst.MAX_NUM + LogConst.EXTRA_NUM;             logNum -= delNum;             self.removeOverflowLog(delNum);         }     }

Spring AOP、嵌套调用失效及解决

加入注解

复制代码
1
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)

获取当前代理的接口

复制代码
1
2
3
4
5
public interface ICurrentAopProxyService<T> {     default T getCurrentProxyService() {         return (T) AopContext.currentProxy();     } }

需要嵌套调用的Service实现它

调用的时候改写代码

复制代码
1
2
3
4
5
public SysMerchantVersion selectByMerchantId(Long merchantId) { return getCurrentProxyService().getOne(new QueryWrapper<SysMerchantVersion>() .lambda() .eq(SysMerchantVersion::getMerchantId, merchantId)); }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是活泼芹菜最近收集整理的关于Spring AOP对嵌套方法不起作用的解决的全部内容,更多相关Spring AOP对嵌套方法不起作用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(167)

评论列表共有 0 条评论

立即
投稿
返回
顶部