@RefreshScope导致AOP切面重复执行源码分析

前言

公司服务中引入了Nacos做配置中心,通过@RefreshScope注解可实现配置实时刷新。在某个AOP切面中发现使用@RefreshScope后,切面方法重复执行了两次,什么原因导致的呢?我们开始今天的源码分析

Tips:需要spring aop源码基础,否则很难看懂。

测试demo

java 复制代码
@Aspect
@Component
@RefreshScope
public class TestAspect {

    @Value("${abcde.huang}")
    private String name;

    @Pointcut("execution(public * com.ht.service.impl.TestService.sayHelloByName(..))")
    public void sayHelloByName() {
    }

    @Before("sayHelloByName()")
    public void beforeSelect(JoinPoint point) {
        System.out.println("aop"+name);
    }
}
java 复制代码
@Service
public class TestServiceImpl implements TestService {

    @Override
    public String sayHelloByName(String name) {
        return name + ",hello!";
    }
}
java 复制代码
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
       ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
        TestService bean = run.getBean(TestService.class);
       bean.sayHelloByName("test");
    }
}

源码分析

AOP第一次增强,往上看在哪里执行的 这里感觉很诡异,测试demo里只有一处使用了aop,不应该是两个,我们继续往上看,这个List在哪构造的。 继续往上看,重点关注这个this.advised.getInterceptorsAndDynamicInterceptionAdvice方法。 继续往里面看

java 复制代码
private List<Advisor> advisors = new ArrayList<>();
@Override
public final Advisor[] getAdvisors() {
    return this.advisors.toArray(new Advisor[0]);
}
public void addAdvisors(Collection<Advisor> advisors) {
    if (isFrozen()) {
       throw new AopConfigException("Cannot add advisor: Configuration is frozen.");
    }
    if (!CollectionUtils.isEmpty(advisors)) {
       for (Advisor advisor : advisors) {
          if (advisor instanceof IntroductionAdvisor) {
             validateIntroductionAdvisor((IntroductionAdvisor) advisor);
          }
          Assert.notNull(advisor, "Advisor must not be null");
          this.advisors.add(advisor);
       }
       adviceChanged();
    }
}

到这里问题已经很清楚了,spring中存在两个"testAspect"bean,导致aop责任链重复执行切面方法。 这里也进一步验证了前面的分析。

总结

当我们在实际项目中遇到问题时,往往并不清楚问题的关键所在。本文采用打断点的方法,逐层从下而上分析源代码,以找出问题的根源。

当切面类TestAspect(加了@Aspect)加上@RefreshScope时后会生成scopedTarget.testAspect和testAspect两个bean,造成切面方法执行两次。具体@RefreshScope为什么会额外生成scopedTarget.testAspect这个bean,我将在另一篇文章中解析。

相关推荐
weixin_4569042710 分钟前
C# 中的回调函数
java·前端·c#
大鱼七成饱16 分钟前
Rust 多线程编程入门:从 thread::spawn 步入 Rust 并发世界
后端·rust
程序员水自流18 分钟前
MySQL InnoDB存储引擎关键核心特性详细介绍
java·数据库·mysql
码事漫谈22 分钟前
深入剖析:C++、C 和 C# 中的 static
后端
码事漫谈26 分钟前
AI智能体全球应用调查报告:从“对话”到“做事”的变革
后端
Chen不旧30 分钟前
easyexcel实现excel读取
java·excel·easyexcell
码界奇点44 分钟前
Spring Web MVC构建现代Java Web应用的基石
java·前端·spring·设计规范
绝无仅有1 小时前
某大厂跳动Java面试真题之问题与解答总结(二)
后端·面试·github
绝无仅有1 小时前
某大厂跳动Java面试真题之问题与解答总结(三)
后端·面试·架构
板板正1 小时前
EasyExcel实现普通导入导出以及按模板导出excel文件
java·excel