I have a requirement to intercept every thrown exception and do something with it. I am using this part of code:
@Aspect
@Component
class Advice
{
@AfterThrowing(pointcut = "execution(* mail.service..*.*(..))", throwing = "throwable")
public void sendError(Throwable throwable)
{
System.out.println("exception thrown");
}
}
This somehow does not work as I expected. This pointcut seems to 'affect' only the public methods(which is expected from Spring AOP, I suppose?) but it prints the String only in certain methods, for example, methods that are declared in my Spring configuration class(i guess its because they are initialized before the app starts) and not in the other ones.
I tried to get this aspect working for any exception thrown, but I had no success. Is this somehow connected with the fact that I am using Spring AOP and not full AspectJ?
Also, my project is written in Kotlin(I wrote the aspect in Java so IJ can support it), will this have an impact on using AspectJ? I had a lot of troubles to get it working (because of final classes) and I am wondering if it's going to be a lot harder when I start writing more advanced AspectJ code.
Thanks!
Yes, Spring AOP only works for Spring components and only for public methods (plus protected and package-protected ones for CGLIB proxies). It also does not work for self-invoked methods like this.doSomething()
because those do not go through the proxy. Only if your exceptions escalate outside a method called via proxy, Spring AOP will be able to intercept it.
AspectJ with LTW (load-time weaving) or CTW (compile-time weaving) does not have any of those limitations, plus you can also handle exceptions in constructors, not just in methods.
Never having used Kotlin before, I cannot tell you what possible problems might be there, but final classes should not be a problem as such because AspectJ instruments the classes' bytecode directly, not via proxies. Just give it a try.
BTW, just in case you only use Spring because of AOP: You do not need to use Spring at all in order to apply AOP to your classes because AspectJ is 100% independent of Spring. You can use them together or not, your choice. I for example never use Spring, but just Java SE + AspectJ.