This is my Aop Aspect that I have created to run after my main app throws an error.
package com.demo.aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyAroundAspect {
@Around("execution(* com.demo.aop.*.getFortune(..))")
public Object aroundAdviceDemo(ProceedingJoinPoint thePJP) throws Throwable
{
System.out.println("run this before the fortune method");
Object result = null;
try {
result = thePJP.proceed();
}
catch(Exception exc)
{ //this should run but is not running
System.out.println("Catching the " + exc.getMessage());
}
System.out.println("Run this after the fortune service");
return result;
}
}
This is my trafficFortuneservuce class which has a method that is throwing an error and I am trying to catch that error using my @Around advice.
package com.demo.aop;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TrafficFortuneService {
public String getFortune(boolean tripwire)
{
if(tripwire)
{ //this is running but it should go to the advice catch block
throw new RuntimeException("Inside run time exception in the fortune service");
}
return "Today is your lucky day";
}
}
This is my main method class where I am running my app.
package com.demo.aop.app;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.demo.aop.Account;
import com.demo.aop.AccountDAO;
import com.demo.aop.AppConfig;
import com.demo.aop.MemberDAO;
import com.demo.aop.TrafficFortuneService;
public class AroundDemoApp {
public static void main(String[] args) {
//Getting context object
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
TrafficFortuneService theService = context.getBean("trafficFortuneService", TrafficFortuneService.class);
boolean tripwire = true;
String temp = theService.getFortune(tripwire);
System.out.println(temp);
context.close();
}
}
Here is the output, which is printing the message that I have declared in the trafficfortuneservice
class
Exception in thread "main" java.lang.RuntimeException: Inside run time exception in the fortune service
at com.demo.aop.TrafficFortuneService.getFortune(TrafficFortuneService.java:15)
at com.demo.aop.app.AroundDemoApp.main(AroundDemoApp.java:20)