首页 > 解决方案 > 如何在原型作用域bean上应用spring aop方面

问题描述

如何在原型作用域bean上应用spring aop方面

spring 方面是否不适用于原型作用域 bean?我有一个带有几个构造函数参数的原型范围 bean。bean 在运行时使用这些参数进行实例化。

我的弹簧配置是这样的-

@Configuration
@EnableAspectJAutoProxy
public class SpringConfiguration {
  @Bean
  @Scope("prototype")
  public PrototypeBean prototypeBean(SomeDTO dtoArg1, OtherDTO dtoArg2) {
     return new PrototypeBean(dtoArg1, dtoArg2);
  }

  @Bean
  public TestAspect testAspect() {
     return new TestAspect();
  }
}

我正在通过applicationContext获取代码中的bean-PrototypeBean,如下所示-

applicationContext.getBean(PrototypeBean.class, dtoArg1, dtoArg2);

但令人惊讶的是,切面并未在原型 bean 的连接点方法的调用上执行。我确信我创建的切入点是正确的,因为在 Eclipse 中,aspectJ 插件在 joinPoint 方法上显示了 aspectJ 引用的可视标记,这表明切入点是正确的,但不确定为什么它在运行时没有被执行PrototypeBean 的 joinpoint 方法被调用。

我是否以不正确的方式接近容器来获取 bean 或者容器没有机会在这个原型 bean 上编织建议?

感谢是否可以提供任何帮助/建议。

标签: javaspringaspectjspring-aopaspect

解决方案


我用 Spring Boot 2.3.4 尝试了同样的事情,它工作得很好。

是回购。确保您具有以下依赖项EnableAspectJAutoProxy才能正常工作。

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <scope>compile</scope>
    </dependency>

推荐阅读