Skip to content
Advertisement

AspectJ: How to weave an aspect library into a Java project

I build small library (Java and Maven) – using AspectJ. Library must be independent. Library deliver Aspects and Annotations. Function of library is – “call advice when executed a method with specific annotation”. All is ok when I use everything in one module, but problem appers when i separate library and project with classes which advice must be applied. I create simple schema. Schema Library B – my library (aspects and annotations) Project A – project with buisness methods which adivce must be applied Is any posibility to do this?

Advertisement

Answer

According to the AspectJ Maven documentation, chapter “using aspect libraries”, you need to

  • add the aspect library as a regular <dependency>,
  • also add the same dependency (without <version> because it is already assigned in step 1) in the plugin <configuration><aspectLibraries> section as an <aspectLibrary>.

Here is a concrete example:

Aspect library POM, marker annotation and sample aspect:

JavaScript
JavaScript
JavaScript

Now run mvn clean install on the aspect library project so as to install the dependency into your local Maven repo.

Java application POM and sample application:

By the way, in the POM I have also added two optional plugins:

  • One-JAR plugin packages your application with all dependencies (e.g. aspect library and AspectJ runtime) into one artifact, here target/java-app-0.0.1-SNAPSHOT.one-jar.jar. You can just run your application via java -jar target/java-app-0.0.1-SNAPSHOT.one-jar.jar.
  • Exec Maven plugin is useful if you easily want to test your application from the command line via mvn clean install exec:java.

These two are only for convenience, you do not need them if you dislike them.

JavaScript

This little driver application demonstrates that you can now annotate methods with @Marker, in this case only foo and zot, but not bar:

JavaScript

Console log:

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