Skip to content
Advertisement

Implementation of AspectJ example not working

I’m try to implement a simple AspectJ annotation example from https://www.baeldung.com/aspectj. The difference is, that I want to use the annotation at a JUnit TestClass. I googled a while for the solution but don’t find the right hint.

Part of my pom.xml

JavaScript

My Annotation:

JavaScript

My Aspect:

JavaScript
JavaScript

The Advice is mentions to the class annotation, I see it in the logs:

JavaScript

But the log “++++++++test++++++++” is not shown in the console. It executes as the advice is not there. I annotated the class, the testcase and a method as in the example. I tried different settings for my Pointcut but the shown is the best. Then the class is also advised. I don’t know what’s wrong.

Advertisement

Answer

Sorry, I was busy. Assuming that your directory layout is like this:

Maven directory layout

Some sample classes might look like this:

JavaScript
JavaScript
JavaScript
JavaScript

Your POM would be:

JavaScript

Then if you either run mvn clean test or simply import the project into IntelliJ IDEA, the log output will be:

JavaScript

Now if for whatever reason you also want to apply the aspect to the annotated application class, simply

  • move the aspect from src/test/java to src/main/java,
  • remove <scope>test</scope> from aspectjrt and
  • uncomment <goal>compile</goal>.

Then the console log would be:

JavaScript

See? Application class MyClass also gets intercepted in this case.


Update: Concerning why it was not working in your own example, that was because your POM was configured in such a way that Maven Compiler Plugin recompiled your classes after the aspects had been woven my AspectJ Maven Plugin. The result was that the aspect information was lost due to overwritten class files.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement