Throws Advice Example Spring AOP


The same bean program of AOP Advices – Types – Tutorial is used. Change comes in configuration XML file and also slightly in client program. Let us name the modified XML file as applicationContext3.xml.

This method executes when any one bean method throws an exception. Now add a new class PleaseThrowsAdvice implementing ThrowsAdvice interface and override the abstract method afterThrowing() method.

1. The 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 – PleaseThrowsAdvice.java

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

public class PleaseThrowsAdvice implements ThrowsAdvice
{
  public void afterThrowing(IllegalArgumentException e) throws Throwable
  {
    System.out.println("afterThrowing() method of PleaseThrowsAdvice is called");
  }
}

afterThrowing() is a predefined callback abstract method of interface org.springframework.aop.ThrowsAdvice.

Configuration file: applicationContext3.xml





  
  





  
  
    
      pta
    
  


Client Program: Client4.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client4
{
  public static void main(String[] args)
  {
    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext3.xml");

    Student std1 = (Student) ac.getBean("ptaproxy");

    std1.printName();
    std1.printCollege();
    try
    {
      std1.printThrowException();
    }
   catch (Exception e) {  }
 }
}

image

Observe, the afterThrowing() method is called after calling all the methods of Student bean. It is called if any one method of Student bean throws an exception.

When to use throws advice (afterThrowing() method?

When some exception is thrown while a method is being executed, to handle the exception properly, throws advice can be used.

Leave a Comment

Your email address will not be published.