Aspect Example



import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/* @Aspect:It indicates that the class is not a pojo but it is an Aspect.
   Job of the apect is to call particular advice method based on the annotation applied.
 */

@Aspect
public class PassengerAspect {

@Before("execution(** com.Flight.fly(..))")
public void switchOffPhones() {
    System.out.println("Switch off the phones");
}
/* switchOffPhones() advice method will be  called before the fly() method called */

@Before("execution(** com.Flight.fly(..))")
public void bindSeatBelt() {
  System.out.println("Taking seats and bind belt");
}
/* bindSeatBelt() advice method will be  called before the fly() method called */ 

@AfterReturning("execution(** com.Flight.fly(..))")
public void goOut() {
  System.out.println("Goes out from the Plane");
}
/* goOut() advice method will be  called after the fly() method called */  

@AfterThrowing("execution(** com.Flight.fly(..))")
public void askMoneyBack() {
  System.out.println("Asking for money back");
}
/* askMoneyBack() advice method will be  called if the fly() throws an exception */  
}