AOP with AspectJ

Recently I read AspectJ in Action by Ramnivas Laddad for the second time. Since I first read the book about three years ago, I haven’t used AspectJ in a real project yet. Generally speaking I think that AOP techniques aren’t applied that often in practice.

I think this should change, so I put together some sensible arguments for AOP. After that we’ll have a quick look at AspectJ. I’d like to emphasize the word quick here, because there’s a lot of information out there. If you’d like to read more about AOP, you may check out the following links:

Why AOP?

Suppose you’re building a web application. The more you code the more features you’d like to add. More features translate to more concerns in your application: you might want to add logging, security and persistence just to name a few. These concerns are crosscutting concerns because you need to add them in various places in your application. Of course you’ll create one single class (OOP-style) that’ll handle logging but this class has to be called in a lot of different places throughout your application. The same thing holds true for the other concerns and you probably end up with a system like this:

Crosscutting concerns scattered all over your code

Suddenly your excellently organized code gets polluted with totally different aspects of the desired features. As more and more aspects are scattered over your code, it will be harder to read and you’ll have a hard time figuring out where your business logic is.

Luckily, you can avoid this if you reorganize the different aspects into separate classes: there’ll be one for logging, security, persistence and so on. This keeps your business logic code concise and to the point. Furthermore it’ll be easier for you if you’d like to change the behavior of these concerns – just change the corresponding aspects. This leads to a system with aspects in different modules separated from the business logic code:

Crosscutting concerns in separate modules

How to AOP?

The rule of thumb is this: if you have to copy code into different modules of your application over and over again, consider writing an aspect instead, because you might be working on a crosscutting concern. More often than not you already have a separate class and calls on various locations in the code to methods of that class. Instead of calling these methods everywhere in your code, you can put them into an aspect.

Think of a class that handles a sessions for you; whatever a session might be (e.g. one for a database). Now there are some methods that need a session object and the boilerplate code in the methods always looks like this:

public void someMethod(final Session session) {
  try {
    session.startSession();
    // do something
} finally {
  session.endSession();
}

So you’ll have this try-finally block, startSession() and endSession() everywhere in your code where you need to handle a session. A much cleaner solution would be the following:

public void someMethod(final Session session) {
    // do something
}

and an aspect like this:

public void aroundSomeMethod(final ProceedingJoinPoint thisJoinPoint,
                             final Session session) throws Throwable {
  try {
    session.startSession();
    thisJoinPoint.proceed();
  } finally {
    session.endSession();
  }
}

Now you have a single method (aroundSomeMethod()) where you can configure the calls to a session object and all the other methods (e.g. someMethod()) that need a session object will remain small and will contain only business logic.

I wrote a simple example for this and you can browse the code here; have a look at the example package and the Runner class. The code demonstrates how to get rid of boilerplate code and do things the AOP way:

Comparison between conventional coding and AOP

What do you think when looking at the picture? Inversion of control? I think that AOP can be very helpful when designing an application with IoC in mind.

Quick look at AspectJ

I wrote a very simple Hello World application with two aspects: AspectJAspect and AspectJAnnotation. While AspectJ at first introduced a Java-like language to write aspects, with AspectJ 5 it’s possible to write aspects as classes with special annotations: the two aspects I wrote demonstrate both approaches. Second, there’s the code for the example I explained in the previous section.

You can download the Eclipse project as tar.gz or zip or browse the code here. If you’d like to run the project in Eclipse, make sure that you’ve got the AspectJ Development Tools installed.

All the code does is introducing a Main class that has a helloWorld() method. The two aspects AspectJAspect and AspectJAnnotation print some information before and after the helloWorld() method and around the constructor and main() method of the Main class.

If you need step by step instructions – with lots of screenshots – how to setup all this using Eclipse with all that’s necessary to get it running I definitely recommend checking out this great tutorial.

Conclusion

Although the example code doesn’t do very much, it showcases some important things:

  • AspectJ integrates seamlessly into Maven and Eclipse. That are the most important points to check: if something doesn’t work with Maven or Eclipse, it’s probably not worth using anyway. This isn’t true for things that are really cool – if it’s really cool I might be willing to do some cumbersome hacks to us it.
  • AspectJ 5 is very easy to use: some annotations here and there – that’s it. This is a good thing because this way it should be much easier to promote AOP. There are still some weird error messages, but… shush, you don’t have to mention that ;).

Because AOP isn’t common knowledge yet, encourage other programmers to read up on AOP; hand them a copy of AspectJ in Action. If you can’t convince other people to use AOP, use it to increase your own productivity, i.e. start using it for logging, tracing or coding policy enforcement.

8 thoughts on “AOP with AspectJ”

  1. Pingback: Logging with AspectJ

  2. hi i jus went through this article and i really appreciate ur effort in this . can u tell me how exactly this class which i have written for logging using aspects is called by my class where business logic resides. do help in this even if this sounds naive to u. thanks in advance

  3. Hi ramkumar,

    have a look at the weaving process of AspectJ here or here. Although a little bit more abstract, this article might be interesting too.

    Basically, a framework like AspectJ reads your aspects, locates the positions in the code where these aspects should be executed and weaves the additional code into your existing code. In the example of your aspect with some logging statements the code gets weaved into the class with your business logic. This way the resulting class file contains both: the code from your aspect and the code from your class with business logic. So, your class with business logic will not call your class with some logging at all – the code will just be executed at the positions (join points) specified in your aspects.

    By the way: if you wouldn’t weave your aspects into your existing code, the code defined in your aspects will not be executed. This is an ideal way to strip away debug logging statements from your program for a production environment. You would just have to turn off the aspects and that would be it.

    Hope that helps…

    Cheers,
    Christian

  4. hi appreciate ur immediate reply. iam doing a POC. iam stuck in middle. my question is how will the class (where the business logic is implemented) calls the class(where the aspects have been defined).how will i run my code that enables logging?

    do i need any xml file to be in place to say that find aspects class in this place if so where wud i need to declare the path of the xml?

    if iam wrong in my understanding of this concept plz do guide with a solid running example so if i jus run in eclipse i can see a output.

    plz do take the pain in helping me out.
    thanks in advance

  5. Hey Christian,
    the posts are quite informative. Could you please help me with this: I am creating an Aspect which traces all the objects created by a class which is tagged by “@this” notation. Could You please suggest me a way to write an aspect for the above mentioned.

  6. Hi Christian,

    I was unable to run your test program.
    I keep on getting:

    Exception in thread "main" java.lang.NoSuchMethodError: org.christianschenk.aspectjtest.aspects.AspectJAnnotation.aspectOf()Lorg/christianschenk/aspectjtest/aspects/AspectJAnnotation;
    	at org.christianschenk.aspectjtest.Main.helloWorld(Main.java:29)
    	at org.christianschenk.aspectjtest.Main.main(Main.java:24)

    I have added the following jars in the classpath:
    aspectjrt.jar
    aspectjweaver.jar
    along with other jars.

    On a side note why there is no aop.xml file in the project?

    Thanks,
    Ashish

  7. Hi everybody who’s having issue getting the example code to run, if you need step by step instructions – with lots of screenshots – how to setup all this using Eclipse with all that’s necessary to get it running I definitely recommend checking out this great tutorial.

Comments are closed.