Aspectj Cookbook

Recipe 2.4. Weaving Aspects into Jars

Problem

Your want to weave your aspects into code that has already been compiled and collected into a .jar file.

Solution

Use the -inpath command-line option when running the ajc command.

Discussion

The ajc command weaves aspects into Java byte code which can reside in .class files, within a Java .jar library file or a mixture of the two. The following instructions show you how to take the code from Recipe 2.2 and package the MyClass class in a .jar file before weaving the HelloWorld aspect into the library:

  1. Compile the MyClass class using the traditional javac command:

    > javac -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% com/oreilly/ aspectjcookbook/MyClass.java

  2. Package the generated MyClass.class file into a .jar file titled MyApp.jar:

    > jar -cvf MyApp.jar com/oreilly/aspectjcookbook/MyClass.class

  3. Compile the HelloWorld.java aspect using the ajc command, specifying the new MyApp.jar on the command line using the -inpath option:

    > ajc -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% -inpath MyApp.jar com/oreilly/aspectjcookbook/HelloWorld.java

    The -inpath option forces the ajc compiler to extract the Java byte code from the supplied .jar files into the destination directory as specified by the -d option. The ajc compiler then includes that extracted byte code in the aspect weaving process.

  4. If no errors occur during compilation with ajc then you will have successfully woven the classes contained within the MyApp.jar file with the HelloWorld aspect. Because the ajc command extracts the classes from the .jar files supplied to the -inpath option, they are no longer needed to run the application. However, you can optionally re-package your new application in a .jar file of its own using the -outjar option when running the ajc command:

    > ajc -classpath %MY_CLASSPATH% -d %MY_DESTINATION_DIRECTORY% -inpath MyApp.jar - outjar MyAspectOrientedApp.jar com/oreilly/aspectjcookbook/HelloWorld.java

    This produces a MyAspectOrientedApp.jar that contains your application's aspects and classes that can then be run using the traditional java command:

    > java -classpath MyAspectOrientedApp.jar com.oreilly.aspectjcookbook.MyClass

    Before weaving your aspects into a .jar library provided by a third party, make sure that the license covering the library allows you to change the contents. If you don't check that it is ok to change the contents of the .jar file then you could be infringing on the third party's license agreement. For example, the license covering the Java Standard Libraries usually does not support the weaving of aspects into code that resides in the java or javax packages or their subpackages.

See Also

Setting up your environment in order to compile your AspectJ projects from the command line is covered in Recipe 2.1.

Категории