Compile/load time weaving with spring

2019-02-14 10:56发布

问题:

The docs explain that, the LTW has to enabled either through the use of <context:load-time-weaver/> xml instruction or the use of @EnableLoadTimeWeaving annotation. However, I have done neither, but I still see that aspects are woven correctly in my projects!

  1. In this case, I don't think they are woven at compile-time (but are they?), so it's surely got to be load-time-weaving?
  2. Even if that's the case, how does it automatically choose to weave aspects in during load-time? Shouldn't the aspects remain unwoven if they are not turned on using one of the ways mentioned above as the docs say?
  3. I've got the aspectj-weaver in my classpath, but that can't be enough to choose either of these weaving types anyway, can it?

回答1:

Spring AOP does not rely on AspectJ byte code weaving. It just borrows the annotations used to define aspects from the AspectJ project. It is a separately implemented framework that uses run-time proxies to implement aspects. If you have <aop:aspectj-autoproxy /> in your application context then spring is using proxies to implement supported aspects defined on beans that are in the container.

Proxies can only achieve a sub-set of the full capabilities of the actual AspectJ system, basically advice that wraps methods. Due to their nature proxies have following limitations:

  • interception on external calls only (while breaching proxy boundary)
  • interception on public members only (private/protected can't be intercepted)
  • unawareness to local calls (or calls with this or super)

If you want to be able to advise fields for example, you would need to enable the use of Native AspectJ.