@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,我将在另一篇文章中解析。

相关推荐
Rain50915 分钟前
2.1 Nest.js 项目初始化与模块化架构
开发语言·前端·javascript·后端·架构·数据分析·node.js
cjp56019 分钟前
009. ASP.NET WEB API 用户关联esp32设备
前端·后端·asp.net
贺国亚25 分钟前
Text-to-SQL与Analytics-Agent
后端
小熊美家熊猫系统33 分钟前
电子合同技术实现与合规实践
java·开发语言·分布式
云烟成雨TD33 分钟前
Agent Scope Java 2.x 系列【3】从零构建 ReActAgent
java·人工智能·agent
一只叫煤球的猫43 分钟前
ThreadForge 源码解读二:一个 Task 从 submit 到完成,内部到底发生了什么?
java·后端·面试
苏三说技术1 小时前
AgentScope Java 2.0 正式发布了!
后端
ping某1 小时前
一个“日志备份”需求,为什么会牵出整个 Linux 日志系统?
后端·架构
阿狸猿1 小时前
论微服务架构及其应用
java·微服务·架构
血小溅2 小时前
Spring AI 对 Skill/MCP 的支持全景整理
后端