Sub topic 20
When to Move to AspectJ Weaving
This chapter assumes you know how Spring creates proxies, how pointcuts and advice work, and why self-invocation and final methods escape advice. Here you will learn what AspectJ weaving changes, how to use it, and how to decide whether you need it.
What proxies cannot do
Spring AOP intercepts calls that cross a proxy boundary. That design is simple and needs no build changes, but it has hard limits:
- Calls from a method to another method on
thisare not intercepted. - Objects created with
neware not intercepted, because Spring does not manage them. finalclasses andfinalmethods cannot be overridden by a CGLIB subclass.privatemethods are never advised. Only method execution on beans is a join point.- Field access, constructor execution and static method calls are not join points in Spring AOP.
If you hit one of these limits and cannot restructure the code, AspectJ is the next tool.
What weaving does differently
AspectJ does not use proxies. A weaver changes the bytecode of the target class itself and inserts the advice logic into the methods, constructors or field accesses that match. After weaving, a call to this.saveReport(...) runs the advice because the advice code is inside the class.
AspectJ has a much larger set of join points than Spring AOP. It can match method calls and method executions, constructor execution, field reads and writes, static initializers, and exception handlers.
| Feature | Spring AOP (proxies) | AspectJ (weaving) |
|---|---|---|
| Mechanism | Runtime proxy around a bean | Bytecode modified at build or load time |
| Targets | Spring beans only | Any class, including `new` objects |
| Join points | Public method execution on beans (and protected/package-visible with CGLIB) | Methods, constructors, fields, static init, handlers |
| Self-invocation | Not advised | Advised |
| `final` / `private` | Not advised (final) / never advised (private) | Advised |
| Build changes | None | Compiler plugin or Java agent |
| Performance | One proxy hop per call | No proxy hop, advice inlined |
Three weaving modes
AspectJ can weave at three moments.
- Compile-time weaving (CTW). The AspectJ compiler (
ajc) compiles your sources and weaves the aspects into the output classes. - Post-compile weaving. The compiler weaves aspects into already compiled
.classfiles or JARs. Use this when you need to weave a library you do not have the source for. - Load-time weaving (LTW). A Java agent weaves classes as the JVM loads them. Aspects are selected with an
aop.xmlfile.
Compile-time weaving surfaces problems early. A wrong pointcut can produce a compiler warning, and the resulting classes work without special JVM flags. Load-time weaving needs no special compiler, but you must add -javaagent to every JVM start, and it adds some startup cost.
Enabling load-time weaving in Spring
Spring integrates with AspectJ weaving through @EnableLoadTimeWeaving. You also need aspectjweaver on the classpath and an aop.xml file in META-INF.
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
@Configuration
@EnableLoadTimeWeaving
public class LtwConfig {
}Start the JVM with the Spring instrumentation agent or the AspectJ agent:
// JVM argument, not Java code. Shown here as a comment so the example stays runnable:
// java -javaagent:aspectjweaver.jar -jar app.jar
public class LaunchNote {
public static void main(String[] args) {
System.out.println("Start with: java -javaagent:aspectjweaver.jar -jar app.jar");
}
}The matching META-INF/aop.xml names the aspects and the packages to weave:
<aspectj>
<aspects>
<aspect name="com.example.TimingAspect"/>
</aspects>
<weaver options="-verbose">
<include within="com.example.service..*"/>
</weaver>
</aspectj>Keep the include list narrow. Without it, the weaver examines every class that loads, which slows startup.
Writing an aspect that works under both models
The same @Aspect annotation style works in both models, so you can often keep your aspect code and change only how it is applied. This aspect advises any method execution, including calls on this, once it is woven:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class TimingAspect {
@Around("execution(* com.example.service..*(..))")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
try {
return pjp.proceed();
} finally {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(pjp.getSignature().toShortString() + " took " + ms + " ms");
}
}
}Two differences matter. First, a woven aspect is created by AspectJ, not by Spring, so @Component does not make it a bean. To inject Spring beans into it, declare it with @Configurable support or use Aspects.aspectOf(...) through a factory method in configuration. Second, with weaving you should not also enable proxy-based AOP for the same aspect, or advice can run twice.
Transactions and weaving
@Transactional can also use AspectJ mode. Set @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) and add spring-aspects to the classpath. The transaction logic is then woven into the class, so self-invocation, non-public methods and objects created with new are all covered.
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
public class TxConfig {
}This is the fix for the ReportService.saveAll problem from the self-invocation chapter, when you cannot move saveReport to another bean.
Decision criteria
Stay with Spring AOP when the targets are Spring beans, calls cross bean boundaries, and the advice is method-level. This covers most service-layer needs: logging, timing, security checks and transactions. It needs no build changes.
Move to AspectJ when one of these is true:
- You must advise self-invocation and cannot refactor.
- You must advise objects not managed by Spring, such as domain entities.
- You need field access, constructor or static initializer join points.
- You need to advise
finalorprivatemethods. - Proxy overhead is measurable in a hot path.
Costs of weaving
Weaving is not free. Consider these before switching:
- Build complexity. Compile-time weaving needs the AspectJ compiler plugin. IDE support varies, and a misconfigured build can silently produce unwoven classes.
- Operational complexity. Load-time weaving requires a JVM agent in every environment, including tests.
- Debugging. Stack traces contain generated methods such as
ajc$around$..., and the bytecode no longer matches the source. - Broad power. Because weaving reaches every class, a loose pointcut can affect code you did not intend.
Exercise
A PricingService bean calls its own private method applyDiscount(), and you want a timing aspect to measure it. Spring AOP does not measure it. Name the two reasons and the smallest change that would make timing work.
Show answer
Spring AOP does not advise private methods, and the call goes through this, bypassing the proxy. The smallest change that keeps proxies is to move applyDiscount() into another bean, make it non-private, and call it through the injected bean. If that is not possible, use AspectJ weaving, which can advise private methods and calls on this.
Exercise
Which weaving mode would you pick for a third-party JAR you cannot recompile, and why?
Show answer
Post-compile weaving can weave the existing JAR once during the build. Load-time weaving also works, because the agent weaves classes as they load. Plain compile-time weaving from source does not apply, because you do not have the source.