DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Trending

  • AI Agents: A New Era for Integration Professionals
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Useful System Table Queries in Relational Databases
  • System Coexistence: Bridging Legacy and Modern Architecture
  1. DZone
  2. Coding
  3. Java
  4. Different Types of AspectJ Weaving

Different Types of AspectJ Weaving

How each weaving types work, internally.

By 
Axellageraldinc A user avatar
Axellageraldinc A
·
May. 24, 21 · Analysis
Likes (3)
Comment
Save
Tweet
Share
14.7K Views

Join the DZone community and get the full member experience.

Join For Free

AspectJ Weaving

https://unsplash.com/photos/OQ1LDghuOEk

There are different types of weaving on AspectJ, I’m going to share the differences for each weaving type.

If you have grasped the basic concepts of AOP (moreover AspectJ) and want to know the details about different types of AspectJ weaving, which are Compile-time weaving, Post-compile (binary) weaving, and Load-time weaving, do continue reading this article.

Compile-time Weaving

Compile-time Weaving

 (https://www.manning.com/books/aspectj-in-action-second-edition)

The weaving process in compile-time weaving happens (obviously) at compile time. As you can see from the diagram above, the left-hand side describes our source codes which are java files, java classes with @Aspect annotation, and the last one are traditional aspect classes. They are then compiled by ajc (AspectJ Compiler) to be woven into a compiled class called woven system. To give more perspective on this, take a look at several code snippets below.

Target class to be woven:

Java
 




x


 
1
@Component
2
public class Target {
3
  public void greet(String name) {
4
    System.out.println("[Actual] Hi " + name + " from target!");
5
  }
6
}



Before Advice:
Java
 




xxxxxxxxxx
1
16


 
1
@Aspect
2
@Component
3
public class GdnBeforeAspect {
4
  @Before("execution(* greet(..))")
5
  public void beforeGreet(final JoinPoint joinPoint) {
6
    doBefore(joinPoint);
7
  }
8

          
9
  private void doBefore(final JoinPoint joinPoint) {
10
    System.out.println("[ASPECTJ BEFORE]");
11
    System.out.println("Target class' name: " + joinPoint.getTarget().getClass());
12
    System.out.println("Target method's name: " + joinPoint.getSignature().getName());
13
    System.out.println("Target method's arguments: " + Arrays.toString(joinPoint.getArgs()));
14
    System.out.println("[ASPECTJ BEFORE]");
15
  }
16
}



Those 2 code snippets are just regular steps to do if we want to do AOP. The 2 snippets above mean that we want to advise the greet() method (which resides inside Target class) with before advice. Nothing fancy happens in the aspect, it’ll just print some information about the method invocation.

Now, this is where something is getting interesting. Let’s define a plugin inside our pom.xml.

AspectJ Maven Plugin:
XML
 




xxxxxxxxxx
1
22


 
1
            <plugin>
2
                <groupId>org.codehaus.mojo</groupId>
3
                <artifactId>aspectj-maven-plugin</artifactId>
4
                <version>1.11</version>
5
                <configuration>
6
                    <complianceLevel>1.8</complianceLevel>
7
                    <source>1.8</source>
8
                    <target>1.8</target>
9
                    <showWeaveInfo>true</showWeaveInfo>
10
                    <verbose>true</verbose>
11
                    <Xlint>ignore</Xlint>
12
                    <encoding>UTF-8 </encoding>
13
                </configuration>
14
                <executions>
15
                    <execution>
16
                        <goals>
17
                            <!-- use this goal to weave all your main classes -->
18
                            <goal>compile</goal>
19
                        </goals>
20
                    </execution>
21
                </executions>
22
            </plugin>



The AspectJ Maven plugin stated above will weave the aspects when we execute mvn clean compile. Now, let’s try to do just that and see what happens.
If you see inside the target directory (which consists of every compiled class) and open Target.class, you’ll see this.

Target class woven using CTW (Compile-time Weaving):
Java
 




xxxxxxxxxx
1
15


 
1
@Component
2
public class Target {
3
  public Target() {
4
  }
5

          
6
  public void greet(String name) {
7
    JoinPoint var2 = Factory.makeJP(ajc$tjp_0, this, this, name);
8
    GdnBeforeAspect.aspectOf().beforeGreet(var2);
9
    System.out.println("[Actual] Hi " + name + " from target!");
10
  }
11

          
12
  static {
13
    ajc$preClinit();
14
  }
15
}



You see that on lines 7–8, the compiler inserts additional functionality which calls the aspect we defined before. This way, the before advice will be executed before the actual process done by the target. Now you know how CTW works internally.

Post-compile (Binary) Weaving

Post-compile (Binary) Weaving
(https://www.manning.com/books/aspectj-in-action-second-edition)

Basically, binary weaving is similar to CTW (Compile-time Weaving), the weaving process is also done on compile-time. The difference is that with Binary Weaving, we’re able to weave aspects into 3rd party library’s source code. Let’s take a look at the code snippets below.

Add the new library as dependency to our main project’s pom.xml:
XML
 




xxxxxxxxxx
1


 
1
        <dependency>
2
            <groupId>com.axell</groupId>
3
            <artifactId>aspectj-aop-lib</artifactId>
4
            <version>0.0.1-SNAPSHOT</version>
5
        </dependency>



Advising greetFromLib() method which exists inside our 3rd party library added previously:

Java
 




xxxxxxxxxx
1
16


 
1
@Aspect
2
@Component
3
public class GdnBeforeAspect {
4
  @Before("execution(* greetFromLib(..))")
5
  public void beforeGreetLib(final JoinPoint joinPoint) {
6
    doBefore(joinPoint);
7
  }
8

           
9
  private void doBefore(final JoinPoint joinPoint) {
10
    System.out.println("[ASPECTJ BEFORE]");
11
    System.out.println("Target class' name: " + joinPoint.getTarget().getClass());
12
    System.out.println("Target method's name: " + joinPoint.getSignature().getName());
13
    System.out.println("Target method's arguments: " + Arrays.toString(joinPoint.getArgs()));
14
    System.out.println("[ASPECTJ BEFORE]");
15
  }
16
}



At this point, we know that greetFromLib() exists inside our 3rd party library, which means in form of .jar file instead of our own written source codes. We need to do several modifications to our AspectJ Maven plugin to accommodate this.

Adding our third-party lib into weave dependency to be woven:
XML
 




xxxxxxxxxx
1
13


 
1
<plugin>
2
...
3
                <configuration>
4
                    ...
5
                    <weaveDependencies>
6
                        <weaveDependency>
7
                            <groupId>com.axell</groupId>
8
                            <artifactId>aspectj-aop-lib</artifactId>
9
                        </weaveDependency>
10
                    </weaveDependencies>
11
                </configuration>
12
...
13
</plugin>



Now that we’ve added necessary information to our AspectJ maven plugin, we simply just have to execute mvn clean compile again, and let’s see what changes inside our target directory.

TargetLib class woven using Binary Weaving:
Java
 




xxxxxxxxxx
1
14


 
1
public class TargetLib {
2
  public TargetLib() {
3
  }
4

          
5
  public void greetFromLib(final String name) {
6
    JoinPoint var2 = Factory.makeJP(ajc$tjp_0, this, this, name);
7
    GdnBeforeAspect.aspectOf().beforeGreetLib(var2);
8
    System.out.println("[ACTUAL] Hi " + name + " from target lib!");
9
  }
10

          
11
  static {
12
    ajc$preClinit();
13
  }
14
}



Similar to what we’ve observed from CTW, the TargetLib class (in which the source code exists on 3rd party library, we don’t host the source code in our main project) got woven by Binary Weaving by using a similar mechanism.

Load-time Weaving

Load-time Weaving
(https://www.manning.com/books/aspectj-in-action-second-edition)
Load-time weaving happens when the classes are about to be loaded into JVM. This means that after compilation, nothing will be added into our compiled classes (unlike CTW and Binary Weaving).
  • Deploy an application.
  • VM initializes the weaving agent.
  • The weaving agent loads all aop.xml files (Yes, we can define multiple aop.xml files and everything gets loaded).
  • Weaving agent loads listed aspects in aop.xml files.
  • The system starts normal execution.
  • VM loads classes during execution (as usual).
  • The VM notifies the weaving agent whenever it loads a class.
  • The weaving agent (after being notified), inspects the to-be-loaded class to determine if any of the aspects need to be woven to the to-be-loaded class.
  • If so, the weaving agent will weave the class and the aspect.
  • The woven byte code will be loaded to VM and used.

Comparison Between Different Types of Weaving

Based on this research paper, these are the comparison results (compared to No-AOP implementation).

Compared to No AOP Execution time (%) CPU Usage (%) Memory Usage (%)
CTW +3.41 -8.5 +3.24
LTW +7.32 -4.56 +30.69
CTW and LTW compared to No-AOP implementation
  • The execution time of CTW is slightly faster than LTW. In my opinion, it’s because for CTW, the weaving process happened on compile-time, meaning that there is no operation overhead on runtime to do the weaving.
  • CPU usage for CTW is also slightly lower than LTW. In my opinion, the reason is the same as the first point above.
  • Memory usage for CTW is considered pretty significantly lower than LTW. In my opinion, the reason is the same as the other 2 points above.

Conclusion

I hope with this article, you guys can have a deeper overview of different types of weaving, specifically on AspectJ.

AspectJ

Published at DZone with permission of Axellageraldinc A. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!