Can view the tutorials best in Google Chrome, Mozilla Firefox, Opera, higher version of Internet Explorer

Spring AOP Throws Advice Example With Complete Explanation

Spring » On Jul 28, 2012 | { 5 Comments }

Will see how to work with Throws Advice in spring AOP.

  • In this type of Advice, we implement services which are executed when ever the business logic of the method throws an exception.  For creating a Throws Advice our class must implement ThrowsAdvice interface.
  • ThrowsAdvice is a marker interface given in org.spfw.aop.*; package, and there are no methods in this interface to provide implementation :-)
  • while creating a ThrowsAdvice class in spring AOP, we should implement our services in a method called afterThrowing() with 1 or 4 parameter(s).
  • In fact, afterThrowing() method is not given in ThrowsAdvice, but we should implement our services in afterThrowing() method only because when ever an Exception is occurred in the business logic then the IOC container internally calls afterThrowing() method to apply the services.

Syntax For ThrowsAdvice Implementation

public class Client implements ThrowsAdvice
{
   public void afterThrowing(Exception e)
   {
       // our services
   }
}
[ or ]
public class Client implements ThrowsAdvice
{
   public void afterThrowing(Method m,Object args[],Object target,Exception e)
   {
       // our services
   }
}

In case of single parameter, only Exception details are accessible, but in case of 4 parameter method, apart from Exception details we can also access method name, method parameters.  At the time of creating ThrowsAdvice, the method afterThrowing() can write any number of times, i mean we can write individual afterThrowing() methods for each Exception separately.

If we write multiple afterThrowing() methods in a class then the IOC container will give the preference like follows..

  • Verify whether afterThrowing() method is available with specific Exception type as parameter or not, if exist then the container calls that afterThrowing() method and executes services implemented in it.
  • If a specific Exception type of afterThrowing() method is not available, then container verifies whether an afterThrowing() method with 4 parameters exist or not if exist then executes the services in it.
  • If 4 parameters afterThrowing() is not exist in the class then the container verifies whether an afterThrowing() method with super class Exception parameter (Exception e) exists or not, if exists then executes the services implemented in it

Example On Spring AOP ThrowsAdvice

Files required…

  • MyImplClass.java
  • MyInterFace.java
  • MyThrowsAdvice.java
  • OurLogic.java
  • spconfig.xml

MyInterFace.java

package java4s;

public interface MyInterFace
{
    void m1();
}

MyImplClass.java

package java4s;

public class MyImplClass implements MyInterFace
{
    public void m1(){

        int java4s = 10/0;
        System.out.println("Am in business method..");

    }
}

MyThrowsAdvice.java

package java4s;

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

public class MyThrowsAdvice implements ThrowsAdvice
{        

    //First preference
    public void afterThrowing(ArithmeticException e)
    {
        System.out.println("This is from ArithmeticException method");
    }

    //Second preference
    public void afterThrowing(Method m, Object args[], Object target,Exception e)
    {
        System.out.println("Am from 4 parameters method called from "+m.getName());
    }

    //Third preference
    public void afterThrowing(Exception e)
    {
        System.out.println("Fom single parameter method");
    }

}

OurLogic.java

package java4s;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class OurLogic
{
    public static void main(String args[])
    {
        Resource res = new ClassPathResource("spconfig.xml");
        BeanFactory factory = new XmlBeanFactory(res);

        MyInterFace inter =(MyInterFace)factory.getBean("id3");
        inter.m1();
    }
}

spconfig.xml

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
            "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

 <bean id="id1" class="java4s.MyImplClass" />
 <bean id="id2" class="java4s.MyThrowsAdvice" />
 <bean id="id3" class="org.springframework.aop.framework.ProxyFactoryBean">

      <property name="proxyInterfaces" value="java4s.MyInterFace" />
      <property name="interceptorNames" >
                  <list>
                       <value>id2</value>
                   </list>
       </property>
       <property name="target">
               <ref bean="id1"/>       
       </property>     

 </bean>

</beans>

Output:

 

Explanation:

  • Actually we know 10/0 will gives arithmetic exception, in MyThrowsAdvice.java i have written afterThrowing(ArithmeticException e) so IOC will executed this method only in the about output.
  • While you are executing this application, if you remove afterThrowing(ArithmeticException e) method then IOC will give the preference to afterThrowing(Exception e), and then to afterThrowing(Method m, Object args[], Object target,Exception e).
 

What you are thinkig....

5 Responses to “Spring AOP Throws Advice Example With Complete Explanation”
  1. naidu says:

    ” Actually we know 10/0 will gives arithmetic exception, in MyThrowsAdvice.java i have written afterThrowing(ArithmeticException e) so IOC will executed this method only in the about output.
    While you are executing this application, remove this method then IOC will give the preference to the afterThrowing(Method m, Object args[], Object target,Exception e), if we remove this preference goes to afterThrowing(Exception e)”

    But I found in practical as The Preference order is

    1) afterThrowing(ArithmeticException e)
    2) afterThrowing(Exception e)
    3) afterThrowing(Method m, Object args[], Object target,Exception e)

  2. Java4s says:

    @Naidu

    You are correct ;)

    The correct order is…

    1) afterThrowing(ArithmeticException e)
    2) afterThrowing(Exception e)
    3) afterThrowing(Method m, Object args[], Object target,Exception e)

    Thanks for letting us aware of this.

    [Article Updated_On 13th Sept 2012]
  3. KiranV says:

    You have applied and updated the Naidu’s comment at your explanation for example.. But description of Throws Advice before example still shows wrong order.. Please update there also.

  4. Ramu says:

    But Practically I got this order

    1) afterThrowing(ArithmeticException e)
    2) afterThrowing(Method m, Object args[], Object target,Exception e)
    3) afterThrowing(Exception e)

    Thanks,
    Ramu

  5. Lakshman says:

    Hi Ramu,

    how u got this can u explain in simple way.

    we got

    1) afterThrowing(ArithmeticException e)
    2) afterThrowing(Exception e)
    3) afterThrowing(Method m, Object args[], Object target,Exception e)

    so,that we also correct our answer.

If you want a pic to show with your comment, go get a gravatar !
Please post your questions on Java4s Answers forum

Name*
Ask a Question ?
or
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Tutorials
Hibernate Recent Posts
Spring Recent Posts
Struts Recent Posts
Recomandded Links Current & UpComing Tutorials Java4s.com
Tutorials Online :
spring Hibernate struts Json Ajax Log4j Log4j
coreJava Servlets


UpComing :
Servlets, Jsps
is optimized for learning java technologies, all the examples in this site are constantly reviewed to avoid errors. While using this site you agree to have read and accepted our terms of use and privacy policy
Especially i have prepared this blog by keeping fresher's in mind, however it will be very useful for real time developers too.


© 2013 Java4s All rights reserved. | strPro4Tut v(2.0) Theme designed by str-Graphics.com