skip to content

AOP Model & the @AspectJ Style

The @AspectJ programming model as Spring uses it: the vocabulary, enabling auto-proxying, declaring @Aspect beans, naming reusable pointcuts, and introductions. Start here before pointcut syntax, since these terms are what interviewers ask you to define.

part ofSpring Frameworkoverview, primer and where to startread it →
on this pageshow

questions

29

How do you declare an aspect with @Aspect and make Spring actually apply it? What steps are required?

level: juniorimportance: must knowfreq 80%

answer

  1. @Aspect marks, @Component registers
  2. @Aspect alone is NOT a bean
  3. @EnableAspectJAutoProxy (Boot auto)
  4. proxy-based, not weaving
  5. self-invocation bypasses advice

basics

~20 s

Put @Aspect on the class to mark it as an aspect, and also register it as a Spring bean (e.g. add @Component so it is scanned). Then enable AOP with @EnableAspectJAutoProxy (Spring Boot does this automatically).

solid answer

~40 s

Three things are needed. First, annotate the class with @Aspect (from AspectJ, org.aspectj.lang.annotation) to mark it as an aspect holding pointcuts and advice. Second, register it as a Spring bean — @Aspect alone does NOT make it a bean; typically add @Component so component-scan picks it up, or declare an @Bean. Third, enable aspect auto-proxying: @EnableAspectJAutoProxy on a @Configuration class (or the equivalent XML <aop:aspectj-autoproxy/>). Spring Boot enables this automatically via AopAutoConfiguration when AspectJ is on the classpath. Without the bean registration the aspect is invisible; without auto-proxying Spring never creates the proxies that invoke the advice. Note Spring uses @AspectJ annotations for configuration but its own proxy-based runtime, not full AspectJ weaving.

code

java · 18 lines
java
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect          // marks it as an aspect (AspectJ annotation)
@Component        // registers it as a Spring bean so Spring can find it
public class AuditAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logEntry() {
        System.out.println("entering service method");
    }
}

// Somewhere in configuration (not needed in Spring Boot):
// @Configuration
// @EnableAspectJAutoProxy
// public class AopConfig {}

go deeper

for a junior

Know the two annotations: @Aspect to mark, @Component to register, and that Boot enables AOP for you.

for a middle

Explain the auto-proxy BeanPostProcessor and why @Aspect alone is invisible; know proxy vs weaving.

for a senior

Discuss JDK vs CGLIB proxy selection and the self-invocation limitation as a consequence of proxying.

for a principal

Contrast Spring AOP proxying with AspectJ LTW when constructor/field/self-call interception is required; reason about bean-post-processor ordering.

**What an aspect is.** In Aspect-Oriented Programming (AOP) a *cross-cutting concern* (logging, security checks, transactions, metrics) is code that would otherwise be scattered across many methods. An **aspect** is a module that captures such a concern in one place. It combines **pointcuts** (expressions selecting *where* to act — which method executions) with **advice** (the code to run — `@Before`, `@After`, `@Around`, `@AfterReturning`, `@AfterThrowing`). **@Aspect.** `@org.aspectj.lang.annotation.@Aspect` marks a class as an aspect. Spring reuses AspectJ's *annotation syntax* but runs it with **Spring AOP** (runtime proxies), not AspectJ's compile/load-time weaving. So you write `@Aspect`/`@Before` etc., but the interception is done by dynamic proxies. **Registering it as a bean — the key gotcha.** `@Aspect` by itself is just metadata; it does **not** turn the class into a Spring bean and Spring will not detect it. You must register the aspect as a bean by the normal means: - add a stereotype like `@Component` (or `@Service`) so `@ComponentScan` picks it up, **or** - declare it with an `@Bean` factory method in a `@Configuration` class, **or** - an XML `<bean>` definition. A very common beginner bug is annotating a class only with `@Aspect`, seeing nothing happen, and not realizing the bean was never created. **Enabling auto-proxying.** Spring only weaves aspects if aspect auto-proxying is turned on. You do this with `@EnableAspectJAutoProxy` on a `@Configuration` class, or `<aop:aspectj-autoproxy/>` in XML. This imports the `AnnotationAwareAspectJAutoProxyCreator`, a `BeanPostProcessor` that: (1) finds all `@Aspect` beans, (2) reads their pointcuts, and (3) wraps matching target beans in proxies (JDK dynamic proxies if the target implements interfaces, CGLIB subclass proxies otherwise). When a method on the proxy is called, the proxy consults the matching advice. **Spring Boot.** With `spring-boot-starter-aop` (or AspectJ on the classpath), `AopAutoConfiguration` enables `@EnableAspectJAutoProxy` for you, so you usually only need `@Aspect` + `@Component`. **Why proxies matter for behavior.** Because Spring AOP works through proxies, advice only fires on **external** calls that go through the proxy. A **self-invocation** (one method in a bean calling another `this.method()`) bypasses the proxy and therefore bypasses the advice — a classic surprise unrelated to how you declared the aspect. **Summary checklist:** `@Aspect` (mark) + bean registration (`@Component`/`@Bean`) + auto-proxying enabled (`@EnableAspectJAutoProxy` or Boot). Miss any one and the advice silently never runs.

  • You added @Aspect and @Component but the advice never runs. What are the likely causes?
    Auto-proxying may be off (missing @EnableAspectJAutoProxy and not a Boot app with the AOP starter); the pointcut may not match; the target bean may not be a Spring bean; or the call is a self-invocation on the same instance, which bypasses the proxy.
  • Does @Aspect on its own create a Spring bean?
    No. @Aspect only marks the class as an aspect. You must register it separately as a bean (via @Component, @Bean, or XML) or Spring will not instantiate it and its advice will never apply.

saying these in an interview costs you the question

  • Believing @Aspect automatically registers the class as a Spring bean
  • Thinking Spring AOP does full AspectJ bytecode weaving by default
  • Forgetting that auto-proxying must be enabled (assuming it is always on outside Boot)
  • Expecting advice to fire on internal self-invocation calls

context

open as a page

What is a cross-cutting concern, and why does AOP exist to handle things like logging, security, and transactions?

level: juniorimportance: must knowfreq 80%

basics

~20 s

A cross-cutting concern is a responsibility (like logging, security, transactions) needed by many parts of an app but not part of any one's core job. AOP pulls that repeated code into one place instead of copying it everywhere.

open as a page

What does @EnableAspectJAutoProxy do in a Spring application?

level: juniorimportance: must knowfreq 70%

basics

~10 s

It turns on Spring's support for @AspectJ-style aspects. Spring then scans for @Aspect beans and automatically wraps matching beans in proxies so the aspect's advice runs around their methods.

open as a page

What is a named pointcut in Spring AOP, and how do you declare one with @Pointcut?

level: juniorimportance: must knowfreq 60%

basics

~10 s

A named pointcut gives a pointcut expression a name so you can reuse it. You declare it by annotating an empty, void-returning method with @Pointcut("...expression..."); the method name becomes the pointcut's name.

open as a page

Define the core AOP vocabulary: aspect, join point, pointcut, and advice. How do they relate?

level: middleimportance: must knowfreq 85%

basics

~20 s

An aspect is the module holding a cross-cutting concern. A join point is a point where code could run (in Spring, a method call). A pointcut is an expression selecting which join points. Advice is the code that runs at those matched points.

open as a page

How does AnnotationAwareAspectJAutoProxyCreator actually create proxies, and why is it a BeanPostProcessor?

level: middleimportance: must knowfreq 55%

basics

~20 s

It's a BeanPostProcessor, so Spring runs it after each bean is created. In postProcessAfterInitialization it checks if any aspect's pointcut matches the bean; if so it returns an AOP proxy that wraps the bean instead of the raw object.

open as a page

Walk through declaring an aspect in XML with <aop:aspect>, <aop:pointcut>, and the advice elements. How do you bind advice methods and reuse a named pointcut?

level: middleimportance: must knowfreq 45%

basics

~10 s

Inside aop:config, add <aop:aspect ref="bean">. Declare a named <aop:pointcut id="..." expression="..."/>, then attach advice like <aop:before pointcut-ref="..." method="..."/>. Each advice element names the POJO method and the pointcut to match.

open as a page

When several advice methods in the SAME @Aspect apply to the same join point, in what order do they run?

level: seniorimportance: must knowfreq 50%

basics

~20 s

Within one aspect, advice runs in a fixed precedence by type: @Around, then @Before, then @After, @AfterReturning, @AfterThrowing. But two advices of the SAME type at the same join point have undefined order — you cannot rely on method declaration order.

open as a page

What is an introduction in Spring AOP, and what does @DeclareParents do?

level: juniorimportance: should knowfreq 15%

basics

~20 s

An introduction adds a new interface (and a default implementation) to advised beans. @DeclareParents declares which interface to add, which beans get it, and which class implements it, so the proxy now implements that extra type.

open as a page

What is schema-based (XML) AOP configuration in Spring, and what does the <aop:config> element do?

level: juniorimportance: should knowfreq 35%

basics

~10 s

It configures aspects in XML instead of with @Aspect annotations. The aop:config element (from the aop namespace) holds aspect definitions; Spring reads it and wraps matching beans in proxies that run your advice.

open as a page

What is the default instantiation (lifecycle) model of a Spring @Aspect, and why does it matter for shared state?

level: middleimportance: should knowfreq 45%

basics

~20 s

By default an aspect is a singleton: one shared aspect instance for the whole application context, just like an ordinary singleton bean. So any fields in the aspect are shared across all advised objects and all threads.

open as a page

In Spring Boot, how is aspect auto-proxying enabled, and how does it differ from a plain Spring app?

level: middleimportance: should knowfreq 45%

basics

~10 s

Spring Boot enables it automatically via AopAutoConfiguration when aspectjweaver is on the classpath, so you normally don't add @EnableAspectJAutoProxy. In a plain Spring app you must add the annotation yourself.

open as a page

Write a @DeclareParents declaration and explain each of its attributes (value, defaultImpl) and the field type.

level: middleimportance: should knowfreq 18%

basics

~10 s

Put @DeclareParents on a field in an @Aspect. The field's type is the interface to introduce, value is an AspectJ pattern for target beans (e.g. "com.example.service.*+"), and defaultImpl is the class implementing that interface.

open as a page

How do you compose named pointcuts using &&, || and !?

level: middleimportance: should knowfreq 45%

basics

~10 s

Combine named pointcuts inside another @Pointcut (or advice) expression with && (both match), || (either matches) and ! (negation). Example: @Pointcut("serviceMethods() && !readOnlyMethods()").

open as a page

How do you write around advice in schema-based AOP, and what must the advice method's signature look like?

level: middleimportance: should knowfreq 33%

basics

~10 s

Use <aop:around pointcut="..." method="..."/>. The referenced POJO method must take a ProceedingJoinPoint as its first parameter and call proceed() to run the target. Its return value becomes the method's result.

open as a page

What do the perthis and pertarget aspect instantiation models do in Spring AOP, and how must the aspect bean be scoped?

level: seniorimportance: should knowfreq 25%

basics

~20 s

perthis creates a new aspect instance for each unique object executing a matched join point (each unique 'this'/proxy); pertarget creates one per unique target object. Both are non-singleton, so the aspect bean must be declared with prototype scope so Spring can create multiple instances.

open as a page

What is weaving, what is the target object, and how does Spring AOP perform weaving compared to AspectJ?

level: seniorimportance: should knowfreq 60%

basics

~20 s

Weaving is linking aspects into your code so advice actually runs. The target object is the real bean being advised. Spring weaves at runtime by wrapping the target in a proxy; AspectJ can weave at compile time or class-load time.

open as a page

Explain the proxyTargetClass and exposeProxy attributes of @EnableAspectJAutoProxy and when you'd set each.

level: seniorimportance: should knowfreq 40%

basics

~10 s

proxyTargetClass=true forces CGLIB class proxies instead of JDK interface proxies. exposeProxy=true publishes the current proxy via AopContext.currentProxy() so a bean can call its own advised methods through the proxy instead of bypassing it.

open as a page

After introducing an interface with @DeclareParents, how do you actually call the new methods, and where does the mixin's state live?

level: seniorimportance: should knowfreq 20%

basics

~20 s

You hold the proxied bean reference and cast it to the introduced interface, then call its methods. The state lives in the defaultImpl instance that backs the proxy — typically one instance per advised bean — not in the original target object.

open as a page

How do you reference a named pointcut declared in a DIFFERENT aspect class, and what role does the pointcut method's visibility play?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Use the fully-qualified reference: ClassName.pointcutName() (or the full package path). The pointcut method must be visible enough — make it public (or protected/package-private) so other aspects can reference it; a private @Pointcut is only usable inside its own class.

open as a page

What is <aop:advisor> and how does it differ from <aop:aspect>? When would you wire a plain bean as an advisor?

level: seniorimportance: should knowfreq 40%

basics

~20 s

aop:advisor pairs a pointcut with a reusable advice bean that already implements a Spring Advice interface (like MethodInterceptor). aop:aspect instead groups multiple advice methods on a plain POJO. Advisors are how tx:advice transactions get applied.

open as a page

How do you control ordering between multiple aspects, and how does that differ from ordering within one aspect? When would you split advice across aspects for this reason?

level: principalimportance: should knowfreq 30%

basics

~20 s

Order whole aspects with @Order or by implementing Ordered — lower value = higher precedence, runs first on entry. This is the ONLY way to get deterministic ordering, because two same-type advices inside one aspect are unordered. So split advice that must be ordered into separate, @Order-ed aspects.

open as a page

As a principal engineer, how do you decide when a concern belongs in an aspect versus explicit code, and what are the risks of over-using AOP?

level: principalimportance: should knowfreq 35%

basics

~10 s

Use aspects for truly cross-cutting, orthogonal plumbing (transactions, security, metrics) that would otherwise be duplicated everywhere. Keep business rules in explicit code. Over-using AOP hides behavior, complicates debugging, and creates 'action at a distance'.

open as a page

Compare schema-based XML AOP with @AspectJ annotation-based AOP. What are the semantic differences, limitations, and when would you deliberately choose XML?

level: principalimportance: should knowfreq 30%

basics

~20 s

Both are proxy-based Spring AOP using the same AspectJ pointcut language and produce identical proxies. XML keeps advice metadata outside the class (good for third-party beans or externalized config); annotations keep it cohesive. XML supports only singleton aspects; @AspectJ also supports perthis/pertarget.

open as a page

What is an 'introduction' (inter-type declaration) in AOP, and how does it differ from advice?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

An introduction adds a whole new interface and its implementation to an existing object, so the advised bean gains extra methods it never declared. Advice only wraps behavior around existing method calls; introduction adds new capabilities.

open as a page

Can a named @Pointcut declare parameters, and how are they used to bind values into advice?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Yes. The @Pointcut method's parameters become the pointcut's parameters. Binding designators like args(), this(), target() and @annotation() tie a matched value to a named parameter, and advice with the same parameter names receives that value.

open as a page

As a BeanPostProcessor, what ordering and eligibility hazards does the auto-proxy creator introduce, and how do you reason about which beans actually get advised?

level: principalimportance: nice to knowfreq 22%

basics

~20 s

Because proxying happens in a BeanPostProcessor after init, any bean created before that processor is active — like other BeanPostProcessors and their dependencies — won't be proxied. Aspects and AOP infrastructure beans are also skipped by design.

open as a page

When would you reach for a @DeclareParents introduction versus alternatives, and what are its limitations in Spring AOP versus full AspectJ?

level: principalimportance: nice to knowfreq 10%

basics

~20 s

Use an introduction to give many beans a uniform interface/capability without editing each class — e.g. change-tracking. Prefer plain interfaces or composition when you can edit the classes. Spring can only introduce interfaces via proxies; full AspectJ weaving can add fields and methods to the class itself.

open as a page

How would you organize named pointcuts across a large codebase, and what maintainability and matching pitfalls do you watch for?

level: principalimportance: nice to knowfreq 20%

basics

~20 s

Centralize shared selections in one or a few public @Pointcut declaration classes (a CommonPointcuts library), give each an intent-revealing name, compose smaller pointcuts into bigger ones, and keep raw designators out of advice. Watch package-based expressions that silently stop matching after refactors.

open as a page