AspectJ <aop:after-throwing>

After throwing advice runs when a matched method execution exits by throwing an exception. It is declared using <aop:after-throwing/> tag.

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 AspectJ XML Configuration.

BusinessService.java

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

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

BusinessImpl.java

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 = 10 / 0;
    }
}

2. Configure Spring AOP and AspectJ support

Create Spring-Business.xml and write the following code

Spring-Business.xml

<aop:config>
    <aop:aspect ref="businessAspect">
        <aop:pointcut id="businessExp"
            expression="execution(* com.kruders.spring.aop.BusinessImpl*.*(..))" />
  
        <aop:after-throwing
            method="afterThrowing"
            pointcut-ref="businessExp"/>
        
    </aop:aspect>
</aop:config>

3. Aspect Class

Now write a Aspect which will profile our business method.

BusinessAspect.java

package com.kruders.spring.aspect;
 
public class BusinessAspect {
    public void afterReturning() {
        System.out.println("After returning method is called");
    }
}

4. Helper Class

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

Main.java

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("businessService");
        try {
            businessService.doSomeThing();
        } catch (ArithmeticException 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