DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Using AspectJ’s @AfterThrowing Advice in your Spring App

Using AspectJ’s @AfterThrowing Advice in your Spring App

Roger Hughes user avatar by
Roger Hughes
·
Oct. 09, 11 · Interview
Like (1)
Save
Tweet
Share
35.18K Views

Join the DZone community and get the full member experience.

Join For Free

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:
@Aspect
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"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">                                                                        
                           
    <!-- Enable annotation based AOP definitions -->
    <aop:aspectj-autoproxy/>

    <bean id="exceptionHandler"
       class="example_10_annotations.afterthrowing_annotation.IncidentThrowsAdvice"/>

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

The important line in this file is:

<!-- Enable annotation based AOP definitions -->
    <aop:aspectj-autoproxy/>

...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);

    myExampleBean.run();

...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)
 at ...THE REST HAS BEEN REMOVED FOR CLARITY...
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

AspectJ Spring Framework Advice (programming) app

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Java REST API Frameworks
  • Java Code Review Solution
  • A Beginner's Guide to Infrastructure as Code
  • Custom Validators in Quarkus

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: