Before Advice Example Spring AOP

Practically, an advice is a method called along with the actual business method. Now when to call the advice? Is it before the business method or after? There comes 4 combinations of advices.

  1. Before advice: It is an advice called before the execution of the actual business method. To put other way, it is an advice called before a joinpoint. A joinpoint is a point in the business code where the piece of code of advice is be added (in other sense, where the advice method should be executed). That is, before the execution of actual method, the advice is executed.
  2. After returning advice: It is an advice (method) called after the execution of a business method.
  3. Around advice: An advice that is executed before and also after the execution of business method (before and after joinpoint). It is the mostly used and powerful advice.
  4. Throws advice: It is an advice executed only when the business method throws an exception.

The concept of joinpoints, matched by pointcuts, is the key to AOP which distinguishes it from older technologies offering only interception. Pointcuts enable advice to be targeted independently of the Object-Oriented hierarchy. For example, an around advice providing declarative transaction management can be applied to a set of methods spanning multiple objects (such as all business operations in the service layer).

To the previous normal program, let us add one-by-one all the advices (finally all the four advices in one program). Let us start with before advice.

Before Advice

The same Student bean of the previous code is used without any modification. Change comes in configuration XML file and also very slightly in client program. Let us name the modified XML file as applicationContext1.xml.

1. The same bean program used in AOP Advices – Types – Tutorial is used and reproduced here.

Bean Program – File Name: Student.java

public class Student
{
  String name;         				// just two variables
  String college;

  public void setName(String name)    		// just two set methods
  {
    this.name = name;
  }
  public void setCollege(String college)
  {
    this.college = college;
  }
  public void printName()            		// 3 print methods to print variables
  {
    System.out.println("Student Name is " + name);
  }
  public void printCollege()
  {
    System.out.println("Student College is " + college);
  }
  public void printThrowException()
  {
    throw new IllegalArgumentException();
  }
}

Add a new class – PleaseCallBeforeMethod.java

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class PleaseCallBeforeMethod implements MethodBeforeAdvice
{
  public void before(Method method, Object[] args, Object target) throws Throwable
  {
    System.out.println("Before method of PleaseCallBeforeMethod is called");
  }
}

before() is a predefined abstract callback method of interface MethodBeforeAdvice.
We will use the parameters of the before() method later.

Note that the first parameter of before() method is an object of java.lang.reflect.Method. It is the method (target method) that is called (or invoked) after executing the before() method. Array Object[] args refers all the arguments passed to the target method and Object target refers the actual object which is calling the method.

applicationContext1.xml

The earlier applicationContext.xml is modified and named as applicationContext1.xml.





  
  



  

  
  
    
      pcbm
    
 



Here, the interceptor method belongs to pcbm and obviously it is before() method. An interceptor intercepts the normal execution flow of bean program and executes its own method before calling each actual method of the bean.

Observe the interceptorNames property. This property tells (ProxyFactoryBean) what objects (advices) should be applied to proxied bean. In the above code, it is PleaseCallBeforeMethod class for which a proxy bean is to be created.

One of the roles of ProxyFactoryBean is gluing the classes. Observe Student class and PleaseCallBeforeMethod are two different entities which are no way connected at all. To connect them, here comes ProxyFactoryBean. See the code. ProxyFactoryBean is glued to Student (through student1) with target attribute and PleaseCallBeforeMethod (through pcbm) with interceptorNames property.

When the client calls pcbm object which includes before() method, a new proxy for the class PleaseCallBeforeMethod is created by Spring container and called. The proxy object also should be mentioned (named as pcbmproxy) in the XML file. Now the client calls pcbmproxy instead of pcbm. The proxy object pcbmproxy calls before() method before executing each method of Student class. It is the habit of Spring to use always proxy classes and proxy objects instead of the actuals.

Client Program to run: Client2.java

Observe the getBean() method parameter is pcbmproxy and not pcbm.

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client2
{
  public static void main(String[] args)
  {
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext1.xml");

    Student std1 = (Student) ac.getBean("pcbmproxy");
                          			// call the proxy object and not actual object pcbm
    std1.printName();
    std1.printCollege();
    try
    {
      std1.printThrowException();
    }
    catch (Exception e) {  }
  }
}

image

Observe, prior to the execution of each method of bean, the before() method is called.

When to use before advice (before() method

Before method is used to intercept the actual business logic method and do some action before the business method is executed. For example, as in the above code, you may want to add some security measure before the debit method is executed like checking the role of the clerk in the bank (whether he is permitted to affect the money transfer). This code can be placed in an advice (before advice) and called. This is how AOP separates the business logic with the aspect (security code). before() is an abstract method of interface org.springframework.aop.BeforeAdvice.

image
strong>MoneyTransferPoxy
that implements
Observe, there exists < MoneyTransfer interface. When the client looks for MoneyTransfer application and starts calling its methods, instead the methods of proxy are executed which then assigns the calls to a method interceptor known as advice. Advice in turn invokes the actual MoneyTransfer instance (called as MoneyTransferTarget).

Leave a Comment

Your email address will not be published.