经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Spring?AOP对嵌套方法不起作用的解决
来源:jb51  时间:2022/1/3 12:31:21  对本文有异议

Spring AOP对嵌套方法不起作用

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

代码如下:

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

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

要解决这个问题

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

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

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

加入注解

  1. @EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)

获取当前代理的接口

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

需要嵌套调用的Service实现它

在这里插入图片描述

调用的时候改写代码

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

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

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号