Tag Archives: aop

AOP: Spring aop vs AspectJ

If you are using Spring framework, it is easy to implement Spring AOP. Ease of implementation comes with some limitations like you can only use aspects with spring managed beans and only methods can be used as pointcuts. Another limitation is that you cannot apply aspects for method calling another in same class. Whereas AspectJ does not have these limitations.

The reason behind this is the way Spring and AspectJ implements AOP. Spring uses runtime weaving whereas AspectJ uses load time weaving. Spring implements proxy based approach. Where it adds a proxy wrapper aound your class, and every call to the class method, has to go through the proxy wrapper.

AspectJ implement load time waving by actually manipulating the bytecode using its compiler while class is loaded to JVM.

References:
http://kamalmeet.com/tag/aop-2/
https://en.wikipedia.org/wiki/AspectJ
http://stackoverflow.com/questions/26325732/spring-aop-with-aspectj-load-time-weaving
http://www.springindepth.com/book/aop-load-time-weaving.html
http://stackoverflow.com/questions/1606559/spring-aop-vs-aspectj

AOP- Understanding terms

In last few posts on AOP I have mentioned basics of AOP, and some sample implementations- http://kamalmeet.com/category/aop/

I will discuss some formal AOP terms here

JoinPoint: A well defined point in execution of a application. A point where something is happening in the applicaiton. For example when a method is called, an object is instantiation, an exception is being thrown etc.

Advice: The code that is to be executed at a particular joinpoint.

Pointcut: Collection of joinpoints where advice has to be applied.

A very good explanation of joinpoint & pointcut- http://stackoverflow.com/questions/15447397/spring-aop-whats-the-difference-between-joinpoint-and-pointcut

Aspect: Combination of pointcuts and advice, programmed in a class. For example see loginaspect class

Weaving: When do we add aspects to actual code- compile time, run time (Spring), load time (AspectJ)

Target Object: object whose execution flow is modified by an AOP process.

Introduction: Process by which you modify target object, by declaring additional methods or fields.

Types of advice:

Before: Before starting the execution

After: After completion of execution

After Throwing: After an exception is thrown

After Returning: After normal execution (no exception thrown)

Around: Before and After execution

Refer: http://docs.spring.io/spring/docs/4.0.1.RELEASE/spring-framework-reference/htmlsingle/#aop-introduction-defn

AOP – Logging utility

For basics of AOP refer

http://kamalmeet.com/aop/aspect-oriented-programming/
http://kamalmeet.com/aop/aspect-oriented-programming-implementation/

Here is a simple logging example using aspectj

package com.my.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * This is class implementing logging aspect. This is a generic class which can
 * be embedded into any piece of code for implementing logging.
 * 
 * @author kamalmeet
 * @version 1.0
 */
@Component
@Aspect
public class LoggingAspect {

	private static final Logger LOG = Logger.getLogger(LoggingAspect.class);;
	

	private static final String POINT_CUT = "execution(* com.my.package.*.*(..))";

	/**
	 * This method is used to log action before entering into point-cut method.
	 * 
	 * @param joinPoint
	 */
	// @Before(POINT_CUT)
	@Before(POINT_CUT)
	public void logBefore(JoinPoint joinPoint) {
		LOG.info("Entering function: "+ joinPoint.getSignature());
		
	}

	/**
	 * This method is used to log action after returning from point-cut method.
	 * 
	 * @param joinPoint
	 */
	@AfterReturning(POINT_CUT)
	public void logAfterReturing(JoinPoint joinPoint) {
		LOG.info("Exiting successfully from function: "+
				joinPoint.getSignature());
	}

	/**
	 * This method is used to log error in case some exception condition
	 * occurred in the given point-cut method.
	 * 
	 * @param joinPoint
	 */
	@AfterThrowing(POINT_CUT)
	public void logAfterThrowing(JoinPoint joinPoint) {
		LOG.error("Exiting with exception thrown from function: "+
				joinPoint.getSignature());
	}
}

Aspect Oriented Programming- Implementation

In my last post I talked about AOP basics. Here I will try to take up aspectj implementation of AOP.

Continuing from last example where I had a simple employee class.

public class Employee {
int id;
String name;

public Employee(int id, String name)
{
this.id=id;
this.name=name;
}

public void work()
{
System.out.println(“Employee:”+ name+” is working”);
}
}

In last post I mentioned how Employee will need to maintain a bookKeeper to maitain start and end work. Whereas same can be achived throuogh AOP in a cleaner way, that is without disturbing Employee at all.

You will need to add aspectj libraries. If you are using Maven it is easy


org.aspectj
aspectjrt
RELEASE


org.aspectj
aspectjtools
RELEASE

If you are using spring, you will need to tell config file that I am using aspects. In my case I am using java based configuration so I will add following in config file.
@Configuration
@EnableAspectJAutoProxy

And then modify your BookKeeper code to tell it that it should execute its methods before and after any class’s method under test package executes.

@Component
@Aspect
public class BookKeeper {

java.util.Date date= new java.util.Date();
/**
* This method records when employee has started working
*/
@Before(“execution(* com.test.*.*(..))”)
public void employeeStartsWorking()
{
System.out.println(“Employee has started working”+new Timestamp(date.getTime()));
}

/**
* This method indicates when employee has stopped working
*/
@After(“execution(* com.test.*.*(..))”)
public void employeeEndsWorking()
{
System.out.println(“Employee has ended working”+new Timestamp(date.getTime()));
}

}

Aspect Oriented Programming

In object oriented programming, each object or class is made up of some properties and behavior. For example an Employee object might have properties like employee id, name etc and behavior like works.

so a simple Employee class would look like

public class Employee {
int id;
String name;

public Employee(int id, String name)
{
this.id=id;
this.name=name;
}

public void work()
{
System.out.println(“Employee:”+ name+” is working”);
}
}

But in real world a lot of things are happening around objects, for example lets say a bookkeeper needs to take a note of everytime an employee starts working and finishes working.

public class BookKeeper {

java.util.Date date= new java.util.Date();
/**
* This method records when employee has started working
*/
public void employeeStartsWorking()
{
System.out.println(“Employee has started working”+new Timestamp(date.getTime()));
}

/**
* This method indicates when employee has stopped working
*/
public void employeeEndsWorking()
{
System.out.println(“Employee has ended working”+new Timestamp(date.getTime()));
}

}

And my Employee class should be modified to

public class Employee {
int id;
String name;
BookKeeper bookKeeper=new BookKeeper();

public Employee(int id, String name)
{
this.id=id;
this.name=name;
}

public void work()
{
bookKeeper.employeeStartsWorking();
System.out.println(“Employee:”+ name+” is working”);
bookKeeper.employeeEndsWorking();
}
}

The challenge here is that my Employee should now be aware of BookKeeper and maintain its calls. Also it would need to actually handle error conditions (what if bookKeeper is null).

AOP or Aspect oriented programming comes to rescue here. Wikipedia states “In computing, aspect-oriented programming (AOP) is a patented[1] programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.”

Cross cutting concerns are the functionalities which are distributed accross the application but are not part of any core module. So for example, we have employee class, manager class, consultant class all implemeting work and book keeper keeoing record. So Book keeper needs to be available to all these objects, though it is not part of their core functionality. AOP recommends to move these functionality out of class and provides methods and tools for this.

Some frequently occuring cases for AOP are logging (ever class has need for logging, but it is not part of core functionality), transaction management, authentication and authrization etc.

I will talk about implementation of AOP part in next post.