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

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 project directory:

Compile-Time Weaving with AspectJ

Then use the following Maven statement to compile the source code:

Result:

Compile-Time Weaving with AspectJ

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

Result:

Compile-Time Weaving with AspectJ

 

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

One thought on “Compile-Time Weaving with AspectJ

  1. Pingback: Enterprise Service Bus Java | Breaking News, Latest News, Headlines & Videos

Add Comment