How to apply spring aop aspect on a prototype scoped bean

595 views Asked by At

How to apply spring aop aspect on a prototype scoped bean

Is spring aspects does not apply to prototype scoped bean ? I have a prototype scoped bean with couple of constructor arguments. The bean gets instantiated at runtime with these arguments.

My spring configuration is like this -

@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();
  }
}

I am getting the bean - PrototypeBean in the code through applicationContext, like this -

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

But surprisingly the aspect is not executing on the invocation of the joinpoint method of the prototype bean. I am sure that the pointcut I created is correct because in eclipse the aspectJ plugin shows the visual marker of the aspectJ reference on the joinPoint method, which shows that the pointcut is correct but not sure why it doesn't get executed at runtime when the joinpoint method of PrototypeBean gets invoked.

Am I approaching the container in incorrect manner to get the bean or the container is not getting the chance to weave the advice on this prototype bean ?

Appreciate if any help / suggestions can be provided on this.

1

There are 1 answers

0
AudioBubble On

I tried the same thing with Spring Boot 2.3.4 and it works just fine.

Here is the repo. Make sure you have the following dependencies in place for EnableAspectJAutoProxy to work.

    <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>