Compile-Time Weaving with AspectJ

In the previous tutorial Introduce about Aspect Oriented Programming, I introduced three ways to insert code using AspectJ: compile-time weaving, post-compile weaving, and load-time weaving. Compile-Time Weaving is the simplest and easiest way to insert the code that will occur when we compile the source code into .class files. How is it in details? Let’s learn more about it in this tutorial.

I will create a new Maven project as an example:

Compile-Time Weaving with AspectJ

Java version 11:

AspectJ dependency:

In fact, inserting the code, from the very beginning, when AspectJ was developed, we will use the AspectJ Development Tool but later we have the Mojo’s AspectJ Maven Plugin plugin with wrapper the AspectJ inside so we just have to use this plugin in Maven project is fine. You declare this plugin as follows:

Now, suppose you have a class that needs to insert code like this:

What I need to insert is that after our application calls the hello() method of the HelloWorld object to print the text “hello”, it will continue to print the text, “Khanh”.

To do this, we first have to have a file to configure the text we need to prepend, the contents of the configuration class will look like this:

I will explain about the @After annotation and its configuration in the incoming post.

The main class to run the example has the following content:

Now we will compile the source code of the HelloWorld class and the source code we need to insert using the aspectj-maven-plugin plugin.

Open Terminal or Console and go to the project directory, then use the following Maven statement to compile the source code:

Result:

Here, you can go to the target directory of the project, and run our application using the following java command to check the results after the compilation:

Result:

 

One thought on “Compile-Time Weaving with AspectJ

  1. thanks for the useful link. But could you please share the gradle version of your pom.xml

    I want to achieve this with gradle.

Add Comment