xetra11
xetra11

Reputation: 8835

Spring AOP adviced methods do not work. My configuration seems ok

I'm trying to create a demo AOP application but it just does not work right. I read through all tutorials and got it working with @RestController but as I tried it with a plain java spring driven application I just can't get it to work. Please review my files and tell me where my mistake lies in.

Application Class

@SpringBootApplication
@ComponentScan("com.xetra.experimental")
@EnableAspectJAutoProxy
public class AoptryoutnowebApplication {

  public static void main(String[] args) {
    SpringApplication.run(AoptryoutnowebApplication.class, args);
    DefaultClassToAspectImpl defaultClassToAspectImpl = new DefaultClassToAspectImpl();
    defaultClassToAspectImpl.doStuff();
  }
}

ClassToAspect Interface

public interface ClassToAspect {
  void doStuff();
}

ClassToAspect Implementation

@Component
public class DefaultClassToAspectImpl implements ClassToAspect {
  @FooAnnotation
  public void doStuff(){
    System.out.println("DoStuff!");
  }
}

Annotation for Pointcut

public @interface FooAnnotation {
}

Aspect Class

@Aspect
public class FooAspect {

  @Pointcut("@annotation(FooAnnotation)")
  public void methods(){
  }

  @Before("methods()")
  public void doAspect(){
    System.out.println("FooAspect before");
  }
}

Upvotes: 0

Views: 64

Answers (2)

M. Deinum
M. Deinum

Reputation: 124536

The problem is you are using a non Spring managed instance by doing new DefaultClassToAspectImpl(). Spring AOP only works for Spring managed beans, because by default Spring AOP is proxy based.

So instead of doing new DefaultClassToAspectImpl() you should be obtaining the instance from the ApplicationContext. When using Spring Boot the SpringApplication.run call returns an ApplicationContext. Here you can use one of the getBean methods to obtain the instance you want.

ApplicationContext ctx = SpringApplication.run(AoptryoutnowebApplication.class, args);
ClassToAspect bean = getBean(ClassToAspect.class);
bean.doStuff();

This way you get the Spring managed

Upvotes: 0

Adam Tychoniewicz
Adam Tychoniewicz

Reputation: 678

Try this:

  1. replace @EnableAspectJAutoProxy with @EnableAspectJAutoProxy(proxyTargetClass = false)

  2. change pointcut to @Pointcut("execution (* your.package..*.*(..)) && @annotation(fooAnnotation))")

Upvotes: 1

Related Questions