Over a million developers have joined DZone.
Platinum Partner

Using AspectJ’s @AfterThrowing Advice in your Spring App

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

This may not be strictly true, but it seems to me that the Guy’s at Spring are always banging on about AspectJ and Aspect Oriented Programming (AOP), to the point where I suspect that it’s used widely under the hood and is an integral part of Spring and I say “widely used under the hood”, because I haven’t come across too many projects that do use AspectJ or AOP in general.

I suspect that part of the reason for this is possibly down to the fact that AOP different is a concept to Object Oriented Programming (OOP). AOP, they say, is all to do with an application’s cross-cutting concerns, which translates to mean stuff that’s common to all classes within your application. The usual example given here is logging and example code usually demonstrates logging all method entry and exit details, which is something that I’ve never found that useful. The other reason that I’ve not seen it used is that the AspectJ documentation is a bit ropey.

Today’s blog is a demonstration of how to implement AspectJ’s @AfterThrowing advice in a Spring application. The idea of the after throwing advice is that you intercept an exception after it’s thrown, but before it’s caught - as shown in this rather simplistic diagram:

I said above that the AOP sample code usually demonstrates logging, and in that respect this blog is no different. The idea in this contrived scenario is to log to a simple Apache Commons log any exceptions thrown. The class that actually does all this is IncidentThrowsAdvice:
public class IncidentThrowsAdvice {

  // Obtain a suitable logger.
  private static Log logger = LogFactory.getLog(IncidentThrowsAdvice.class);

   * Called between the throw and the catch
  @AfterThrowing(pointcut = "execution(* *(String, ..))", throwing = "e")
  public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {

    System.out.println("Okay - we're in the handler...");

    Signature signature = joinPoint.getSignature();
    String methodName = signature.getName();
    String stuff = signature.toString();
    String arguments = Arrays.toString(joinPoint.getArgs());
    logger.info("Write something in the log... We have caught exception in method: "
        + methodName + " with arguments "
        + arguments + "\nand the full toString: " + stuff + "\nthe exception is: "
        + e.getMessage(), e);

The class itself is fairly straight forward. It has one method myAfterThrowing(...), which takes two arguments of type: JoinPoint and Throwable. Taking each of these in turn, JoinPoint just an class that holds information that describes a point within your code. Applying it to this particular after throwing advice means that it’s the point in your code where the exception occurred. The second argument is more straight forward as it’s the actual exception that’s currently being thrown

There are two annotations applied to this class: @Aspect and @AfterThrowing. @Aspect marks the AnyOldExampleBean class as an AspectJ class, whilst the second annotation: @AfterThrowing is more interesting. This annotation tells AspectJ to call the myAfterThrowing() method when an exception occurs. It has two attributes, pointcut and throwing. pointcut defines the circumstances in which the myAfterThrowing() method is called as defined by the expression * *.*(..). This, like the rest of AspectJ seems remarkably badly documented, however you can determine that this signifies a method signature. In this case we’re checking every method in every class. This expression breaks down as follows:

  1. * - The first star is method visibility and or the method return type. The following will work in this example:
    • *
    • public void
    • void
    whereas public on its own throws a BeanCreationException exception when loading the Spring config.
  2. *.* - this represents the package and method, again, using the same wild card formatting; hence, the following are all valid:
    • example_10_annotations.afterthrowing_annotation.Sneeze.sneeze
    • *.*
    • *.sneeze
    • example_10_annotations.*.Sneeze.sneeze
    ...however, example_10_annotations.*.sneeze won’t match for some reason...
  3. (..) - Defines the method arguments. In this example, the following will match:
    • (..)
    • (String, String, int)
    • (String, ..)

Having defined an AspectJ after throwing advice, the next step is to integrate it into the Spring application and this is a matter of adding one line to your Spring config file together with the appropriate schema reference in your <beans>: XML element:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    <!-- Enable annotation based AOP definitions -->

    <bean id="exceptionHandler"

    <!-- The rest of our beans -->
    <bean class="example_10_annotations.afterthrowing_annotation.AnyOldExampleBean">
        <property name="sneeze">
            <ref local="sneeze"/>
    <bean id="sneeze" class="example_10_annotations.afterthrowing_annotation.Sneeze"/> 

The important line in this file is:

<!-- Enable annotation based AOP definitions -->

...as it switches AOP on. The bean definitions that follow it demonstrate how the after throws advice works. The Sneeze class simply throws an exception when its called and the AnyOldExampleBean is a simple test class that calls Sneeze.sneeze(...) as shown below:
public class Sneeze {

   * Throw an exception
  public void sneeze(String arg0, String arg1, int i) throws Exception {
    throw new Exception("Simulate an error");
public class AnyOldExampleBean {

  private Sneeze sneeze;

   * @return
  public Sneeze getSneeze() {
    return sneeze;

   * @param sneeze
  public void setSneeze(Sneeze sneeze) {
    this.sneeze = sneeze;

   * Do something
   * @return
  public void run() {
    try {
      sneeze.sneeze("arg0", "arg1", 42);

    } catch (Exception e) {
      System.out.println("Caught e");
    } finally {
      System.out.println("the end...");


The code to run the above is:

ApplicationContext ctx = new ClassPathXmlApplicationContext("example10_throwsadvice.xml");

    AnyOldExampleBean myExampleBean = ctx.getBean(AnyOldExampleBean.class);


...and when running this code, you should get the following output:

This is the after throwing exception handler
13:41:46,399  INFO ClassPathXmlApplicationContext:456 - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4ce2cb55: startup date [Sun Aug 14 13:41:46 BST 2011]; root of context hierarchy
13:41:46,462  INFO XmlBeanDefinitionReader:315 - Loading XML bean definitions from class path resource [example10_throwsadvice.xml]
13:41:46,863  INFO DefaultListableBeanFactory:555 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@663257b8: defining beans [org.springframework.aop.config.internalAutoProxyCreator,exceptionHandler,example_10_annotations.afterthrowing_annotation.AfterThrowingBean#0,sneeze]; root of factory hierarchy
Okay - we're in the handler...
13:41:47,171  INFO IncidentThrowsAdvice:42 - Write something in the log... We have caught exception in method: sneeze with arguments [arg0, arg1, 42]
and the full toString: void example_10_annotations.afterthrowing_annotation.Sneeze.sneeze(String,String,int)
the exception is: Simulate an error
java.lang.Exception: Simulate an error
 at example_10_annotations.afterthrowing_annotation.Sneeze.sneeze(Sneeze.java:20)
 at example_10_annotations.afterthrowing_annotation.Sneeze$$FastClassByCGLIB$$5c47789.invoke()
 at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
 at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
 at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
Caught e
the end...

As I said above, AspectJ seems very badly documented as can be borne out by the JavaDocs, which if you look through means that the code contains very little documentation, which in turn means that I’m glad I’m not working on it...

Finally, in covering the after throwing advice, this blog only really touches on AspectJ and there are other useful AspectJ advice annotations that I will probably be covering in the near future.



From http://www.captaindebug.com/2011/09/using-aspectjs-afterthrowing-advice-in.html

The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}