Video in progress
What is the difference between Spring AOP and full AspectJ (compile-time or load-time weaving), and when do you need AspectJ?
Spring AOP / AspectJ weaving — Mechanism: JDK dynamic proxy / CGLIB / advice is woven into the bytecode; Join point: method calls only / method, constructor, field get/set, static init; Self-invocation: doesn't work / works; Object created with new: doesn't work / works; Setup: nothing needed / the ajc compiler or…
📖 Answer
| Spring AOP | AspectJ weaving | |
|---|---|---|
| Mechanism | JDK dynamic proxy / CGLIB | advice is woven into the bytecode |
| Join point | method calls only | method, constructor, field get/set, static init |
| Self-invocation | doesn't work | works |
Object created with new |
doesn't work | works |
| Setup | nothing needed | the ajc compiler or -javaagent |
| Pointcut syntax | a subset of the AspectJ syntax | full |
Spring AOP borrows the annotations (@Aspect, @Around) and the pointcut language from AspectJ, but not its weaver. That's why many people think "we use AspectJ" when in fact a proxy is doing the work.
When you'd consider moving to AspectJ:
- a transaction or cache must also work on calls inside a class, and restructuring the code isn't possible (
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)); - you need to inject dependencies into domain objects (entities created with
new) (@Configurable); - the proxy overhead is noticeable on very frequently called methods.
In practice it's rare: the build gets more complicated, "where was this code called from" is harder to follow in the IDE and the debugger, and there are difficulties with native images too. Often the problem is solved by splitting the code into two beans. It's good to say this in an interview: "AspectJ solves the self-invocation problem, but I'd fix the design first".
Sign up to mark studied questions and save your progress.