Internals of Spring Framework and other IoC containers

18,353

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.

Share:
18,353

Related videos on Youtube

Miguel Ping
Author by

Miguel Ping

Nuthin' special :)

Updated on October 24, 2020

Comments

  • Miguel Ping
    Miguel Ping over 3 years

    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?

  • Miguel Ping
    Miguel Ping over 15 years
    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 :)
  • Kevin Day
    Kevin Day over 15 years
    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)
  • Jevgeni Kabanov
    Jevgeni Kabanov over 15 years
    Nope. JDK proxies work only with interfaces, CgLib proxies also work with usual classes.