Spring AOP AfterThrowingAdvice

In this article you will see how to use afterThrowing advice of spring aop. After throwing advice runs when a matched method execution exits by throwing an exception.

For sample code in details, refer the following link. Click Here

1. Business Logic and Implementation

We will first write our business logic and then we will add Spring AOP to profile our business methods.

Create an interface BusinessService and write a following method. We will intercept this via Advice


package com.kruders.spring.aop;
public interface BusinessService {
    void doSomeThing();

Now create a class BusinessImpl.java that implements the above interface.


package com.kruders.spring.aop;
import org.springframework.stereotype.Service;
public class BusinessImpl implements BusinessService {
    public void doSomeThing() {
        System.out.println("Do Something Here");
        int x = 5/0;

2. Aspect Class

Now write a Aspect BusinessAfterThrowing.java which will profile our business method.


package com.kruders.spring.advice;
import org.springframework.aop.ThrowsAdvice;
public class BusinessAfterThrowing implements ThrowsAdvice{
    public void afterThrowing(ArithmeticException e) throws Throwable {
        System.out.println("After throwing method is called");

3. Configure Spring AOP

Create Spring-Business.xml and write the following code


<bean id="businessService" class="com.kruders.spring.aop.BusinessImpl" />
    <!-- Advice -->
    <bean id="businessAdvice" class="com.kruders.spring.advice.BusinessAfterThrowing" />
    <bean id="businessServiceProxy"
    <property name="target" ref="businessService" />
    <property name="interceptorNames">

4. Helper Class

Create Main.java class that loads our Business bean from Spring Context and then calling our business method.


package com.kruders.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kruders.spring.aop.BusinessService;
public class Main {
    public static void main(String args[]) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("Spring-Business.xml");
        BusinessService businessService = (BusinessService)appContext.getBean("businessServiceProxy");
        try { 
        } catch(Exception ae) {

5. Output

When you run the above example you’ll get an output like:

Do Something Here
After throwing method is called

No comments yet.

Leave a Reply