The @Before annotation declares before advice in Spring AOP: a method in an aspect that runs just before a matched method (the join point) executes. You use it for cross-cutting concerns such as logging, authorization checks, input validation and metrics, without changing the target code.
Before advice cannot change the return value and cannot skip the target method, unless it throws an exception. If you need to control or replace the call, use @Around advice.
Spring AOP builds a proxy around each matching bean. A call through the proxy first runs the @Before method, then, if it completes normally, the real method. If the advice throws, the target method is not called and the exception propagates to the caller.
You need the AspectJ annotations and weaver on the classpath. In a Spring Boot project, add the AOP starter for your Boot version, and auto-configuration enables proxying for you. In plain Spring, add @EnableAspectJAutoProxy to a configuration class.
The aspect itself must be a Spring bean, so annotate it with @Component as well as @Aspect.
Calling orderService.placeOrder("book", 2) from another bean logs:
The string in @Before is a pointcut expression. The most common designator is execution.
| Expression | Matches |
|---|---|
execution(* com.example.service.*.*(..)) | Any method of any class in the service package |
execution(public * *(..)) | Any public method |
within(com.example.service..*) | Any method in the package and its subpackages |
@annotation(com.example.Audited) | Methods carrying a custom annotation |
To reuse an expression, name it with @Pointcut and refer to it:
The args(userId, ..) clause binds the first argument to the advice parameter, so you can use it without reading the JoinPoint array. Throwing here blocks the call, which is how before advice enforces a precondition.
When several aspects apply to the same method, use @Order on the aspect class. Lower values run first on the way in.
this.otherMethod() inside the same class bypasses the advice.final classes or methods cannot be proxied by subclassing.Only by throwing an exception. For a conditional skip or a replaced result, use @Around and decide whether to call proceed().
@Before runs prior to the method and cannot affect its return value. @Around wraps the call and can change arguments, the result and whether the method runs.
Typical causes are a missing @Component on the aspect, a pointcut that does not match, auto-proxying not enabled, or a self-invocation that skips the proxy.
Yes, through JoinPoint.getArgs() or by binding them with args(...) in the pointcut.
@Before runs advice ahead of matched methods in a Spring bean through a proxy. Define the aspect as a bean, write a precise pointcut, use JoinPoint or args to inspect the call, and remember that throwing is the only way for before advice to block the target. Use @Around when you need more control.