Weaving Java Binaries using Ant build strategy
Aspect weaving is a process of modifying binary .class
files after compilation in order to inject AOP advice at certain join points.
First of all, you annotate your classes and methods, and then compile. Then you run AspectJ weaver which modifies .class
files, producing new "weaved" versions of them.
Sometimes when you're working on legacy system, Maven build is not available and in a lot of them, the build system is provided by ant macros. Luckily, we can provide a production working example. All you need to do to start using our AOP aspects with an Ant build is to include aspectjrt into your lib path and add these macros to your build.xml
:
<path id="classpath"> <pathelement location="${aspectjrt.jar}"/> </path> <!-- Define aspectj element path --> <path id="aspect.path"> <pathelement path="${aspectj.jar}"/> </path> <!--Responsible to weave/merge the javac binary code result with aj binaries --> <target name="weave-binary"> <iajc showWeaveInfo="true" inpath="${targetdir}" destDir="${targetdir}" fork="true"> <aspectpath refid="aspect.path"/> <classpath refid="ajclasspath" /> </iajc> </target>
Then, include the weave-binary macro into your build target to weaver and modify your .class files. It is very important to call weave-binary after your javac macro. Check a basic example:
<!-- here comes your javac strategy --> <target name="compile"> <echo message="Compile using Java version ${ant.java.version}."/> <javac includeantruntime="false" encoding="UTF-8" srcdir="${sourcedir}" destdir="${targetdir}" classpathref="classpath" /> </target> <!-- This is the final target process that you do before deploy your app / prepare your project package. --> <target name="package" depends="clean, compile, weave-binary"> <!-- here comes your package project behavior --> </target>
Check for more iajc configuration options.
That's it.