Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Spring aspects work internally?

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?

like image 318
M Sach Avatar asked Dec 20 '14 14:12

M Sach


2 Answers

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

like image 128
Andy Dufresne Avatar answered Sep 30 '22 16:09

Andy Dufresne


Still there are two points to clarify here

First one in my post is actually load time weaving not run time weaving

From this link

Load-time weaving (LTW) is simply binary weaving defered until the point that a class loader loads a class file and defines the class to the JVM. To support this, one or more "weaving class loaders", either provided explicitly by the run-time environment or enabled through a "weaving agent" are required.

Second one is compile time weaving

Compile-time weaving is the simplest approach. When you have the source code for an application, ajc will compile from source and produce woven class files as output. The invocation of the weaver is integral to the ajc compilation process. The aspects themselves may be in source or binary form. If the aspects are required for the affected classes to compile, then you must weave at compile-time. Aspects are required, e.g., when they add members to a class and other classes being compiled reference the added members.

like image 45
M Sach Avatar answered Sep 30 '22 16:09

M Sach