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

相关推荐
楚兴2 分钟前
ACP 到底解决了什么?让 IDE 和 Coding Agent 解耦
人工智能·后端·架构
楚兴11 分钟前
DeepSeek Harness 到底在做什么?拆开 Agent 的运行时
人工智能·后端·架构
名字还没想好☜17 分钟前
Go 标准库 flag 包实战:参数解析、子命令、自定义 Value 类型与默认值
开发语言·后端·golang·go
米花米唐19 分钟前
Spring AI 2.0 MCP服务器搭建与使用
后端
程序猿DD35 分钟前
OctaFuse Gateway 2.9.0:用户限流控制、自定义转发头与管理后台升级
后端·api
三千星37 分钟前
Java开发者转型AI工程化Week 5:让RAG学会思考、看见与自检
后端
一个Ai的杂货铺39 分钟前
exit 0 也会撒谎:一个"绿灯盲跑"了一个月的定时任务,尸检报告
后端
hfywmsj39 分钟前
广州餐饮铺位招租的选址架构:流量入口与成本函数分析
java·大数据·jvm·广州餐饮铺位招租
北漂EDA码路40 分钟前
现代 C++20:move、forward 与完美转发,EDA 大型程序为什么离不开它
后端
爪哇岛国人42 分钟前
原来我一直理解错了:实现接口真的必须实现所有方法吗?
java