Skip to content
javahacks.dev
Spring Framework

Spring AOP vs AspectJ and When You Need Load Time Weaving

Compare Spring AOP and AspectJ: proxies versus weaving, supported join points, self invocation, performance, load time weaving and how to choose.

5 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the Spring, Apache Maven, Gradle, JUnit5 and OpenJDK logos.

Both frameworks use the same annotation style and pointcut language, which hides how different their mechanisms are. The mechanism decides what an aspect can intercept.

Spring AOP: proxies

Spring wraps a bean in a proxy. A call enters the proxy, the advice runs, and the proxy calls the target.

java
@Aspect
@Component
class AuditAspect {
    @Before("execution(* com.example.service.*.*(..))")
    void audit(JoinPoint jp) { log.info("calling {}", jp.getSignature()); }
}

What it supports:

  • method execution on Spring-managed beans,
  • JDK dynamic proxies for interfaces, CGLIB subclasses for classes,
  • no change to the compiled classes.

What it cannot do:

  • advise calls from a method to another method of the same object,
  • advise private, final or static methods in a proxy-based setup,
  • intercept constructors, field reads and writes,
  • advise objects created with new.

The self-invocation limit causes the common bug, see self-invocation explained and [@Transactional not working](/library/transactional-not-working-fix-self-called).

AspectJ: weaving

AspectJ changes the bytecode so that the advice is inlined at the join point. Three modes:

WeavingWhenSetup
Compile timeDuring buildAspectJ compiler plugin
Post-compile (binary)After compile, on jarsPlugin step
Load time (LTW)When classes loadJava agent

It supports many more join points: field access, constructor execution, static initialisation, calls, and advice on code in classes that are not Spring beans.

Spring with AspectJ mode

Switch transaction, caching and async advice from proxies to AspectJ weaving:

java
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@Configuration
class TxConfig {}

With weaving in place, @Transactional on a method applies even when called from within the same class and on non-public methods.

Load-time weaving

java
@Configuration
@EnableLoadTimeWeaving
class LtwConfig {}
Shell
java -javaagent:/path/spring-instrument.jar -jar app.jar

An aop.xml in META-INF lists the aspects and the packages to weave:

XML
<aspectj>
  <weaver options="-verbose">
    <include within="com.example..*"/>
  </weaver>
  <aspects>
    <aspect name="com.example.audit.AuditAspect"/>
  </aspects>
</aspectj>

Costs: an agent in the launch command, slower startup because classes are woven as they load, harder debugging, and compatibility questions with tools that also use agents. Compile-time weaving avoids the runtime cost but complicates the build. Native images and AOT processing do not combine well with load-time weaving.

Compared

Spring AOPAspectJ
MechanismProxiesBytecode weaving
Join pointsMethod execution on beansMethods, fields, constructors, more
Self-invocationNot advisedAdvised
SetupNoneCompiler plugin or agent
PerformanceProxy call overheadDirect, near zero overhead
Learning curveLowHigher

Choosing

  1. Cross-cutting concerns on service methods called from other beans: Spring AOP. This covers logging, timing, security and transactions in most applications.
  2. The limit is blocking you, for example you must advise self-calls or domain objects created with new: AspectJ.
  3. First try restructuring. Moving a method to another bean often fixes the self-invocation without weaving.

Examples of AspectJ-only cases

  • Auditing field changes of domain objects.
  • Dependency injection into objects created with new through @Configurable.
  • Advising static utility methods.

Practical advice

Write aspects with the @Aspect annotation style, so they run on either engine. Start with proxies. Introduce weaving deliberately, with a build and runtime test that proves the advice runs, since a missing agent fails silently.

Compile-time weaving with the AspectJ compiler

When an aspect must apply to code that Spring does not proxy, the weaving happens in the build. The AspectJ Maven plugin compiles the aspects and weaves them into the classes:

XML
<plugin>
    <groupId>dev.aspectj</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <version>1.14</version>
    <configuration>
        <complianceLevel>25</complianceLevel>
        <source>25</source>
        <target>25</target>
        <aspectLibraries>
            <aspectLibrary>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
            </aspectLibrary>
        </aspectLibraries>
    </configuration>
    <executions>
        <execution>
            <goals><goal>compile</goal></goals>
        </execution>
    </executions>
</plugin>

The plugin replaces the normal compile step for the aspects, so a build with it needs the same JDK for compiling and running. With weaving done at build time, @Transactional on a private method or a self-call works, because the advice is inside the method body, not in a proxy. The cost is a slower build and a toolchain that every developer must have.

Load-time weaving needs an agent

The alternative to build-time weaving is a Java agent that weaves classes as they load. It requires a JVM flag, and nothing in the code shows it:

Shell
java -javaagent:/opt/agents/aspectjweaver-1.9.24.jar -jar app.jar
java
@Configuration
@EnableLoadTimeWeaving
class WeavingConfig { }

An aop.xml file in META-INF lists the aspects and the packages to weave. Weaving every class slows startup, so list only the packages that need it. The flag is the weak point: a container image or a start script that loses it silently turns the aspects off, and the application runs with no error and no advice. A test that checks one woven behaviour, such as that a method writes an audit record, guards against it.

What a proxy cannot intercept

The practical difference is a short list of join points, and it decides the choice.

Join pointSpring AOPAspectJ
Public method on a Spring bean, called from outsideYesYes
Self-invocation inside the beanNoYes
Private, static or final methodNoYes
Object created with newNoYes
Field read or writeNoYes
Constructor executionNoYes
Classes that are not Spring beansNoYes

A rule such as "audit every write to this field" or "inject dependencies into objects created with new" needs AspectJ, and @Configurable is the Spring feature built on it. If every join point you need is in the first row, Spring AOP is enough and its simplicity wins.

The costs of each choice

Proxies cost a method call and a chain of advice, and need no build changes. Build-time weaving costs build time and tooling, and the runtime is as fast as hand-written code. Load-time weaving costs startup time and a JVM flag. A team that adopts AspectJ for one aspect pays those costs for every developer and every environment, so check whether a design change, such as moving a self-call into another bean, removes the need first.

A decision in three questions

Ask whether the pointcut needs anything beyond a call to a public method of a bean. If not, use Spring AOP. If yes, ask whether the code can change shape to fit, by splitting a class. If that is acceptable, do it. If not, use compile-time weaving, and choose load-time weaving only when the classes to weave come from jars you cannot rebuild.

Revisit the choice when the code changes

The right weaving mode depends on the code that exists today. An application that began with a few aspects on public service methods may grow to need field-level interception, or may drop the aspect that needed AspectJ. Review the decision each year, or when a new aspect is proposed, and ask whether the current mechanism still fits.

Removing an agent or a build plugin that is no longer needed simplifies every environment, and it is a small piece of work that is easy to schedule and easy to forget.

When this does not apply

Applications with no cross-cutting needs use neither. See writing a logging aspect. References: Using AspectJ with Spring and the AspectJ project.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.