In part 1 of this post, we created an Android library containing aspects that could be used to intercept code in an application. However the library would require code changes in order to work with other application, and so was not really reusable as it stood.
In this part, we will modify the sample code to make the library more reusable across multiple applications.
Scenario 2 – The Pointcut in the Application
In this example, the aspect tracing code is kept in the aspect library project, but we will put the pointcut in the application.
Create the Projects
Create an Android application project and library project, and configure them as AspectJ projects in Eclipse, same as for part 1. Then add the library project to the application project, both as an Android library and to the application aspectpath.
Code Changes
1. Aspect Library
Once again put the AspectJ tracing code in the library project, but this time the pointcut has been made abstract.
public abstract aspect BaseTraceAspect { /** Pointcut for tracing method flow tracing */ protected abstract pointcut traceOperations(); before() : traceOperations() { Signature sig = thisJoinPointStaticPart.getSignature(); log("Entering [" + sig.toShortString() + "]"); } /** Implement in subaspect for actual logging */ protected abstract void log(String msg); }
Notice I have also made the log method abstract as well, this leaves it up to the application to determine how it wants to log the tracing output. In general any funcationality that is specific to the application should be made abstract here, and be implemented in the application.
2. Test Application
In the application project, add some code that can be intercepted by the aspect, as for part 1.
Then create another aspect file which subclasses the aspect in the library project. This aspect just implements the pointcut (and in this sample, the logging method as well).
public aspect TraceAspect extends BaseTraceAspect { private final static String TAG = "Aspect-Test"; protected pointcut traceOperations(): execution(* au.com.example.test.**.testMethod(..)); protected void log(String msg) { Log.i(TAG, msg); } }
Run and Verify
Once again run the application and verify in LogCat that the aspect tracing has worked.
The Sample Code
You can download the sample code for this example, aspect-lib-example_2.zip from GitHub. Follow the same instructions as for the previous example for running the sample app.
Conclusion
Now the aspect library project is reusable in other applications. An application would just need to include the library and then override the abstract pointcut to implement a concrete pointcut that is specific to it.
In the last part of this article, we will add another library to the application and show how to apply the aspects to it as well.