views:

609

answers:

2

I've been using spring for some time, but I always wondered how does it work, more specifically, how do they load and weave beans/classes marked only with an interface or @annotation.

For the xml declarations, it's easy to see how spring preprocesses my beans (they are declared in the xml context that spring reads), but for the classes marked only with annotations, I can't see how that works, since I don't pass any agent to the jvm or so.

I believe there is some Java/JVM hook that allows you to preprocess classes by some sort of criteria, but I wasn't able to found out anything on the docs.

Can someone point me to some docs? Is this related to the java.lang.instrument.ClassFileTransformer API?

A: 

The Spring Framework download comes bundled with the source code, so you are free to take a peak at the code yourself (inside the src folder) to find out.

The reference manual is also pretty lengthy (588 pages if you download it as a PDF).

matt b
Thanks, but I was looking for a way of not diving into the spring source... Anyway the PDF does not mention the internals of spring.
Miguel Ping
+9  A: 

Actually by default Spring does not do any bytecode postprocessing neither for XML-, nor annotation-configured beans. Instead relevant beans are wrapped into dynamic proxies (see e.g. java.lang.reflect.Proxy in the Java SDK). Dynamic proxies wrap the actual objects you use and intercept method calls, allowing to apply AOP advices. The difference is that proxies are essentially new artificial classes created by the framework, whereas weaving/bytecode postprocessing changes the existing ones. The latter is impossible without using the Instrumentation API you mentioned.

As for the annotations, the implementation of <context:component-scan> tag will scan the classpath for all classes with the Spring annotations and create Spring metadata placeholders for them. After that they are treated as if they were configured via XML (or to be more specific both are treated the same).

Although Spring doesn't do bytecode postprocessing itself you can configure the AspectJ weaving agent that should work just fine with Spring, if proxies do not satisfy you.

Jevgeni Kabanov
Thanks, great answer! I was kinda puzzled on how could spring or any other framework access my classes without me supplying them to the container, but now it makes sense :)
Miguel Ping
I should point out that the use of Proxy means that you must code to interfaces to use Spring without weaving (Proxy only works with interfaces)
Kevin Day
Nope. JDK proxies work only with interfaces, CgLib proxies also work with usual classes.
Jevgeni Kabanov