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.

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

Now create a class 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 = 10 / 0;

2. Configure Spring AOP and AspectJ support

Create Spring-Business.xml and write the following code


    <aop:aspect ref="businessAspect">
        <aop:pointcut id="businessExp"
            expression="execution(* com.kruders.spring.aop.BusinessImpl*.*(..))" />

3. Aspect Class

Now write a Aspect which will profile our business method.

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

4. Helper Class

Create 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 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 {
        } 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