1. Overview
In this article, we will learn Spring AOP before advice method.
2. Spring AOP before advice
The Before advice method runs before the matching method execution. Use?@Before?annotation to declare a Before advice. This advice cannot prevent or block the target method execution.
3. AOP Before advice example
Let’s see an example for the before advice.
Below beforeController advice will execute before any method executions inside the com.tedblob.controller package. This uses an in-place pointcut expression, meaning @Before annotation has the pointcut expression inside the braces to filter method executions.
@Aspect public class BeforeExample { @Before("execution(* com.tedblob.controller.*.*(..))") public void beforeController() { } }
You can also rewrite the above example using pointcut methods.
Here, we have a separate pointcut method to filter the method executions and it is passed to @Before annotation. Both behaves the same way.
<span class="has-inline-color has-vivid-cyan-blue-color">@Aspect public class</span> BeforeExample { <span class="has-inline-color has-vivid-cyan-blue-color">@Pointcut</span>(execution(* com.tedblob.controller.*.*(..))") public void controllerInvocations() {} <span class="has-inline-color has-vivid-cyan-blue-color">@Before</span>("controllerInvocations()") public void beforeAdvice() { // write your code which needs to be executed before method execution } }
4. Conclusion
In this article, we have seen the Spring before advice along with its examples.