Wednesday, June 4, 2014

Aspect-oriented Programming (AOP) - AJDT - First project

To actually define pointcuts (Pointcuts - 1Pointcuts - 2), advice (Introduction - 2after advice), and aspects in general, AJDT is a useful tool. According to your eclipse version, download instructions are available in AJDT - download.

That is, you open eclipse, go to Help -> Install new Software ; enter the appropriate update site, and install AJDT.

Once installed, you can define an AspectJ project, with classes and aspects.

Creating an AspectJ project:


In the next window, set the project name.

A project that has not initially been set as an AspectJ project, can later be changed (and an AspectJ project can be changed to a normal java project - but if it has aspects, it will fail to compile)

Add a new class HelloWorldAspectsMain

with the following methods:

public static void main(String[] args) {
foo();
}

private static void foo() {
           System.out.println("in foo"); 
}


Then, create the aspect HelloWorldAspect (new -> Other.. -> Aspect) 

The contents of the created file are:

public aspect HelloWorldAspect {

}

Within the brackets add the following code:


pointcut callFoo(): call(* *.foo());
before(): callFoo(){
System.out.println("Hello");
}
after(): callFoo(){
System.out.println("World!");
}

so that the resulting aspect file is:

public aspect HelloWorldAspect {
pointcut callFoo(): call(* *.foo());
before(): callFoo(){
System.out.println("Hello");
}
after(): callFoo(){
System.out.println("World!");
}
}


Run the code as an AspectJ program (when pressing run, this option should appear), and check what happens!

The expected output is:

Hello
in foo
World!

No comments:

Post a Comment