AOP : Aspectj: Logging Example & Tutorial Using Pointcut and AOP XML

Aspectj : Notes, Tutorial & Example

Recently, I was exploring various logging mechanism available in Java and I came across this topic – Aspectj.

I found the AOP – Aspect Oriented Programming approach quite unique (and quite complex to use as well!)

As I learned basics of Aspectj step by step, I kept taking notes of whatever I’ve grasped. Sharing it here.


What is AOP?

AOP is a programming paradigm. It breaks the program logic into distinct parts (called concerns). It is used to increase modularity by cross-cutting concerns.

Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides modularity. But the key unit of modularity is aspect than class.

A cross-cutting concern is a concern that can affect the whole application and should be centralized in one location in code as possible, such as transaction management, authentication, logging, security etc.

Implementation of AOP results into well-modularized implementation of cross cutting concerns.


Why AOP?

It provides the pluggable way to dynamically add the additional concern before, after or around the actual logic. Suppose there are 10 methods in a class as given below:

class A{
public void m1(){...}
public void m2(){...}
public void m3(){...}
public void m4(){...}
public void m5(){...}
public void n1(){...}
public void n2(){...}
public void p1(){...}
public void p2(){...}
public void p3(){...}
}

There are 5 methods that starts from m, 2 methods that starts from n and 3 methods that starts from p.


Understanding Scenario

I have to maintain log and send notification after calling methods that starts from m.

 

Problem without AOP

We can call methods (that maintains log and sends notification) from the methods starting with m. In such scenario, we need to write the code in all the 5 methods.

But, if client says in future, I don’t have to send notification, you need to change all the methods. It leads to the maintenance problem.

Solution with AOP

We don’t have to call methods from the method. Now we can define the additional concern like maintaining log, sending notification etc. in the method of a class. Its entry is given in the xml file.

In future, if client says to remove the notifier functionality, we need to change only in the xml file. So, maintenance is easy in AOP.


Where use AOP?

AOP is mostly used in following cases:
– To provide declarative enterprise services such as declarative transaction management.
– It allows users to implement custom aspects.


AOP Concepts and Terminology

AOP concepts and terminologies are as follows:

  • Join point
  • Advice
  • Pointcut
  • Introduction
  • Target Object
  • Aspect
  • Interceptor
  • AOP Proxy
  • Weaving
  • Cross-cutting concerns

Cross-cutting concerns

Part of logic that spans across entire application. It affects entire application. Such as logging or session mechanism.

cross-cutting-concerns-aspectj

 

 

Join point

Join point is any point in your program such as method execution, exception handling, field access etc.

Advice

Advice represents an action taken by an aspect at a particular join point. There are different types of advices:

  • Before Advice: it executes before a join point.
  • After Returning Advice: it executes after a joint point completes normally.
  • After Throwing Advice: it executes if method exits by throwing an exception.
  • After (finally) Advice: it executes after a join point regardless of join point exit whether normally or exceptional return.
  • Around Advice: It executes before and after a join point.

around-advice-aspectj

 

Pointcut

It is an expression language of AOP that matches join points.

Aspect

It is a class that contains advices, joinpoints etc.


Sum up

A join point is a well-defined point in the program flow.

A pointcut picks out certain join points and values at those points.

A piece of advice is code that is executed when a join point is reached.

Aspects are the unit of modularity for crosscutting concerns. They behave somewhat like Java classes, but may also include pointcuts, advice and inter-type declarations.


AOP Implementations

AOP implementations are provided by:

  • AspectJ
  • Spring AOP
  • JBoss AOP

Core concerns vs Cross cutting concerns

A core concern is a reason that the application exists, the business logic that the application automates. If you have a logistics application that handles shipping freight, figuring out how much cargo you can pack on a truck or what’s the best route for the truck to take to drop off its deliveries might be core concerns.

Cross-cutting concerns are typically implementation details that need to be kept separate from business logic.


Weaving / Aspect weaving

There are a few different ways to inject the AOP code in our application, but one common denominator is that they all require some type of extra step to be applied to our code. This extra step is called weaving.

Compile-time weaving

If you have both the source code of the aspect and the code that you are using aspects in, you can compile your source-code and the aspect directly with an AspectJ compiler.

Post-compile weaving / Binary weaving

If you can’t, or don’t want to use source-code transforms to weave the aspects into the code, you can take already compiled classes or jars and inject aspects.

Load-time weaving

Acts the same way as post-compile weaving / binary weaving but waits to inject aspects into the code until the class loader loads the class file. This requires one or more weaving class loaders.


AOP in Real Life

AOP(Aspect Oriented Programing) is not a technology or a product, its a programming paradigm.

Its one of the principles of DRY (Don’t Repeat Yourself).

The repeating thing here is the aspect or crosscutting concerns. In AOP, these aspects are extracted and then applied to target in a manageable and reusable way.

  • Database transaction management
  • Security check
  • Logging
    Not all loggings are cross cutting concerns. The loggings that specific to the business itself should stay with business code. But the system wide loggings for example, the method calling as a system event that should be logged is cross cutting concerns.
  • Spring has well implemented AOP framework already in place.

Java Example

Following can be the simplest example of using AOP via Aspectj in Java:

//Entry point of application
public class TestAOP {

    public static void main(String[] args) {
       AOPDemo aspectjDemo = new AOPDemo();
       aspectjDemo.testAspectj();
    }
}


public class AOPDemo {
    //testAspectj() is our point of interest. So it will be our Join Point. 
    public void testAspectj() {
        System.out.println("Testing Aspectj");     
    }
}


//This class is Aspect. It contains Advice and Pointcut. 
public aspect MyAspect {

    //Following line is Pointcut: Following piece of advice will run BEFORE execution of testAspectj() method of ANY class.
    before():execution(* *.testAspectj()) {
     
        //Next line is Advice. A piece of code that will be executed at certain pointcuts.  
        System.out.println("Before execution of testAspectj() method");
    }
}

-- -- --

Without Aspectj, running the application will yield output:
> Testing Aspectj

With Aspectj enabled, running the application will yield output:
> Before execution of testAspectj() method
> Testing Aspectj

Notes:

  • AOP is concept/paradigm. Aspectj is its implementation.
  • Need of good logging: Logging is an important component of the software development. A well-written logging code offers quick debugging, easy maintenance, and structured storage of an application’s runtime information.

Video for NetBeans Installation: https://www.youtube.com/watch?v=DgF_5bRH9-Q


References:

Good but a tad complex starting point: http://www.yegor256.com/2014/06/01/aop-aspectj-java-method-logging.html

Intro on AOP with Aspectj explaining why and where it can be used: http://www.christianschenk.org/blog/aop-with-aspectj/

Cross cutting example: http://stackoverflow.com/questions/23700540/cross-cutting-concern-example

Official Aspectj guide: https://eclipse.org/aspectj/doc/next/progguide

AOP in real life: http://makble.com/aop-in-real-world-examples

Brief and to the point explanation: http://www.javatpoint.com/spring-aop-tutorial


Posted

in

by

Comments

13 responses to “Aspectj : Notes, Tutorial & Example”

  1. Trushar Gavit Avatar
    Trushar Gavit

    I read a comment on another post that “WordPress put it in spams”. Why do you use WordPress?

    1. Darpan Dodiya Avatar

      Because its the best CMS out there.

      1. Trushar Gavit Avatar
        Trushar Gavit

        Which language did you use? Do you prefer asp.net to make website?

        1. Darpan Dodiya Avatar

          WordPress is in PHP so its PHP.

          No, apart from some simple Hello World type websites in .NET, I haven’t learned much about Microsoft technologies.

          1. Trushar Gavit Avatar
            Trushar Gavit

            Well, thanks man for information. I am really impressed with your website design and blogs. Most posts are about Dang(my native place).

          2. Darpan Dodiya Avatar

            Anytime 🙂

            I have lived in Vansda for 18 years. I frequently visit Dangs. Which is your hometown? Maybe we can meet some time..

          3. Trushar Gavit Avatar
            Trushar Gavit

            My hometown is Ahwa. Currently, I am studying in Ahmedabad for master’s degree in IT.
            And actually, we were together once. when I came to Nadiad with my friends Hardik Rathod and Deep Halpati. We went to an ice cream parlor. Do you remember?
            I heard about you from them 😅. I am thinking about starting my own website for a blog. But I don’t have any experience and that much knowledge to build a responsive website.

          4. Darpan Dodiya Avatar

            Cool man!

            Have never imagined that we met at some point of time. Glad to have a conversation with you. Trying to stress my memory but couldn’t recollect that ice cream parlor incident. I guess, I’ve become old now. 😛

            Let me know if you need any help setting up your website or blog. I’d be happy to help. 🙂

          5. Trushar Gavit Avatar
            Trushar Gavit

            Yeah 😅. Can you mail me instructions about How to start a website?, Things to be taken care while building a website, Language, and scripting, how to connect to WordPress CMS. It is a nice conversation with you. And thank you again.

          6. Darpan Dodiya Avatar

            Hey buddy! I was out for few days, couldn’t reply you.

            I will connect with you over email soon.

          7. Trushar Gavit Avatar
            Trushar Gavit

            Sure

  2. Trushar Gavit Avatar
    Trushar Gavit

    Did you make this website by yourself?

    1. Darpan Dodiya Avatar

      Yes boss.

      Being a computer engineer, developing website is no rocket science for me.. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *