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
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()));
}
}