After throwing advice runs when a matched method execution exits by throwing an exception. It is declared using @AfterThrowing annotation.
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 Annotation.
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;
@Service("businessService")
public class BusinessImpl implements BusinessService {
public void doSomeThing() {
System.out.println("Do Something Here");
int x = 10 / 0;
}
}
2. Aspect Class
Now write a Aspect which will profile our business method.
BusinessAspect.java
package com.kruders.spring.aspect;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class BusinessAspect {
@Pointcut("execution(* com.kruders.spring.aop.BusinessImpl*.*(..))")
public void businessMethods() { }
@AfterThrowing("businessMethods()")
public void afterThrowing() {
System.out.println("After throwing method is called");
}
}
3. 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){
}
}
}
4. Output
When you run the above example you’ll get an output like:
Do Something Here
After throwing method is called

No comments yet.