How Spring aspects work internally?

M Sach picture M Sach · Dec 20, 2014 · Viewed 10k times · Source

Say Service calls Dao class on which logging aspect(annotational) needs to be applied. I am wondering how aspects actually gets applied.

As per my understanding at the time of DAO injection under Service object, spring finds out that there is some aspect(in this case logging) is configured for DAO, so it injects the proxy object instead of actual target object. Now when actual call is made to any method inside DAO, proxy applies the aspects and then call the actual target object. Is that correct ? Also i believe this is called Run time weaving.

On the other hand same can be done with load time weaving(with javaagent configuration) where byte code manipulation is done for classes on which aspects needs to be applied. So proxy does not come into picture here.

Please correct me if i am wrong as this is the foundation for all spring modules?

Answer

Andy Dufresne picture Andy Dufresne · Dec 20, 2014

Your understanding is right. Spring AOP is proxy-based. Spring uses either JDK proxies (preferred wheneven the proxied target implements at least one interface) or CGLIB proxies (if the target object does not implement any interfaces) to create the proxy for a given target bean.

Unless configured to do otherwise, Spring AOP performs run-time weaving. You can however set up Spring to do load-time weaving through AspectJ. Check the documentation link for more details.

Reference for Spring AOP proxying internals