AspectJ practices from AOP practical classes.
A simple introduction to Aspect Oriented Programming with AspectJ.
AOP (aspect-oriented programming) is a programming style that can be adopted to define certain policies that in turn are used to define and manage the cross-cutting concerns in an application. In essence, it’s a programming paradigm that enables your application to be adaptable to changes.
public class Exe01 {
public static void printHelloWorld(){
System.out.print(" World");
}
public static void main(String[] args){
Exe01.printHelloWorld();
}
}
public aspect Exe01Aspect {
pointcut nome(): execution (* Exe01.printHelloWorld());
before() : nome() {
System.out.print("Hello");
}
void around() : nome(){
//proceed(); Advice is executed after pointcut
System.out.print(" Nobody!"); //without proceed method, advice replaces pointcut
// proceed(); Advice is executed before pointcut
}
after() : nome(){
System.out.print(", DeeCarneiro!!");
}
}
They allow a programmer to specify join points (well-defined moments in the execution of a program, like method call, object instantiation, or variable access). All pointcuts are expressions (quantifications) that determine whether a given join point matches. For example, this point-cut matches the execution of printHelloWorld() method in an object of type Exe01:
pointcut nome(): execution (* Exe01.printHelloWorld());
They allow a programmer to specify code to run at a join point matched by a pointcut. The actions can be performed before, after, or around the specified join point. Here, the advice print on the screen a string after printHelloWorld() method execution:
after() : nome(){
System.out.print(", DeeCarneiro!!");
}
//Intercepts the execution of the method Solve with int type parameter
public pointcut point01() : execution ( void PointcutExample.Solve(int));
//Intercepts the calling of the constructor of the PointcutExample
public pointcut point02() : call (PointcutExample.new());
//Intercepts the calling of the constructor of the PointcutExample with parameters
public pointcut point03() : call (PointcutExample.new(String, int));
//Intercepts the getting of the diff attribute from PointExample class
public pointcut point04() : get (* PointcutExample.diff);
//Intercepts the setting of any attribute from PointExample class
public pointcut point05() : set( * PointcutExample.*);
//Intercepts the calling of any method with int type parameter from PointExample class
public pointcut point06() : call ( * PointcutExample.*(int));
//Intercepts the calling of any method that starts with S on any part of system
public pointcut point07() : call (* *.S*(..));
//Intercepts the execution of any method from PointcutExample method
public pointcut point08() : execution (* PointcutExample.*(..));
//Intercepts the handler of any method within code PointExample.
public pointcut point09() : handler (Exception) && withincode(* PointcutExample.*(..) );
— Help > Eclipse Marketplace and search for AspectJ
— Install AspectJ