skip to content

What is @Before advice in Spring AOP and when does it run?

level: juniorimportance: must knowfreq 70%

answer

  1. Runs before the join point
  2. Cannot skip target — only throwing stops it
  3. JoinPoint gives args + signature
  4. Entry logging / validation use case
  5. Proxy-based: self-invocation bypasses

basics

~10 s

@Before advice is aspect code that runs before a matched method (the join point) executes. It's used for things like logging entry or validating arguments. It runs before, then the real method still runs.

solid answer

~40 s

@Before is an advice type in Spring AOP that executes before the matched join point (typically a method call). You declare it in an @Aspect class with a pointcut expression, e.g. @Before("execution(* com.app.service.*.*(..))"). It commonly handles cross-cutting entry concerns: logging method entry, validating or auditing arguments, security checks. It runs first, then control passes to the target method automatically — @Before cannot decide to skip the target. The only way to stop the target from running is for the @Before body to throw an exception, which propagates and prevents the call. It can optionally take a JoinPoint parameter to read method arguments and signature.

code

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

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.app.service.*.*(..))")
    public void logEntry(JoinPoint jp) {
        System.out.println("Entering " + jp.getSignature().toShortString()
                + " with args " + java.util.Arrays.toString(jp.getArgs()));
        // when this method returns, the target service method runs automatically
    }
}

go deeper

for a junior

Know the definition: runs before the method, used for logging/validation, JoinPoint gives you args.

for a middle

Understand it can't skip the target except by throwing, and how to read args via JoinPoint.

for a senior

Explain proxy semantics, self-invocation limitation, and when to reach for @Around instead.

for a principal

Frame @Before within advice ordering, proxy mechanics, and design tradeoffs vs @Around for validation gates.

## What AOP and advice mean **Aspect-Oriented Programming (AOP)** lets you modularize *cross-cutting concerns* — logic like logging, security, or validation that would otherwise be scattered across many methods. In Spring, you write an **aspect**: a class annotated with `@Aspect` (from AspectJ's annotation set, `org.aspectj.lang.annotation.Aspect`) and registered as a Spring bean (e.g. `@Component`). Inside it you declare **advice** methods that run at chosen points in your program. A **join point** is a point during execution where advice can be applied. In Spring AOP a join point is *always a method execution* (Spring AOP is proxy-based and only intercepts method calls on Spring beans). A **pointcut** is an expression that selects which join points a piece of advice applies to. ## What @Before does `@Before` (`org.aspectj.lang.annotation.Before`) declares **before advice**: the advice method body runs **immediately before** the matched target method executes. After the advice returns normally, Spring proceeds to invoke the target method as usual. ```java @Aspect @Component public class LoggingAspect { @Before("execution(* com.app.service.*.*(..))") public void logEntry(JoinPoint jp) { System.out.println("Entering " + jp.getSignature().toShortString()); } } ``` The string inside `@Before(...)` is a **pointcut expression** (AspectJ syntax). `execution(* com.app.service.*.*(..))` matches any method, any return type, in any class in `com.app.service`, with any arguments. ## Key semantic: @Before cannot prevent the target from running This is the single most important gotcha. `@Before` runs *before* the method, but it has **no control over whether the method runs**. When the advice body finishes normally, the target method is called. There is no "return false to skip" mechanism. The **only** way `@Before` can stop the target from executing is to **throw an exception** — that exception propagates to the caller and the target is never invoked. (If you need to conditionally skip or replace the call, use `@Around` advice with a `ProceedingJoinPoint`, where you decide whether to call `proceed()`.) ## Accessing arguments and signature via JoinPoint An advice method may declare a first parameter of type `org.aspectj.lang.JoinPoint`. Spring injects it automatically. Useful methods: - `jp.getArgs()` — `Object[]` of the method's arguments (read-only; changing the array does not change what the target receives in before advice). - `jp.getSignature()` — a `Signature` describing the method (name, declaring type). - `jp.getTarget()` — the underlying target object. - `jp.getThis()` — the proxy. You can also bind arguments by name using pointcut designators like `args()` instead of pulling them from `getArgs()`. ## Typical uses - **Entry logging / tracing** — record that a method was called and with what arguments. - **Validation / precondition checks** — throw if an argument is invalid (throwing here legitimately aborts the call). - **Security / authorization checks** — throw if the caller is not permitted. - **Auditing** — record who invoked what. ## Ordering and edge cases - Multiple advices on the same join point run in an order controlled by the aspect's `@Order` / `Ordered`. For **before** advice, the *higher-priority* aspect (lower order number) runs **first**. - Spring AOP is **proxy-based**: `@Before` only fires when the method is called *through the proxy* from another bean. **Self-invocation** (a method in the same bean calling another `@Before`-advised method directly via `this`) bypasses the proxy and the advice does **not** run. - Only Spring-managed beans get advised; `private` and (for CGLIB proxies) `final` methods can't be advised. - Requires `@EnableAspectJAutoProxy` or Spring Boot's AOP autoconfiguration (present when `spring-boot-starter-aop` is on the classpath).

  • If @Before advice runs, is the target method guaranteed to run afterward?
    Only if the advice returns normally. If the @Before body throws an exception, it propagates and the target is never invoked. There is no other way for @Before to prevent the call.
  • What annotation and setup are required for @Before to work?
    An @Aspect class registered as a bean (e.g. @Component), plus AspectJ auto-proxying enabled via @EnableAspectJAutoProxy (or Spring Boot's spring-boot-starter-aop autoconfiguration).

saying these in an interview costs you the question

  • Saying @Before can return false / a value to skip the target method
  • Claiming @Before wraps the method and controls proceeding (that's @Around)
  • Thinking self-invocation within the same bean still triggers the advice

context