Advice in Spring AOP

Definition

In the context of Spring AOP (Aspect-Oriented Programming), advice refers to the action taken by an aspect at a particular join point. A join point is a specific point in the execution of a program, such as the execution of a method or the handling of an exception. Advice defines 'when' the aspect's logic should be executed, such as before or after a method call.

Overview

Advice is a core concept in Spring AOP, representing the action that an aspect takes at a join point. There are several types of advice, each specifying when the aspect's logic should be executed relative to the method execution:

  • @Before: Advice that runs before a method execution.
  • @AfterReturning: Advice that runs after a method successfully returns a result.
  • @AfterThrowing: Advice that runs after a method throws an exception.
  • @After: Advice that runs after a method execution, regardless of its outcome.
  • @Around: Advice that surrounds a method execution, allowing for behavior both before and after the method call.

Aspect Terminology

To effectively use aspects in Spring, the framework must manage the objects for which you want to apply aspects. This involves adding beans to the Spring context, enabling the framework to control them and apply the defined aspects. The bean that declares the method intercepted by an aspect is known as the target object.

Figure 6.2 The aspect terminology. Spring executes some logic (the aspect) when someone calls a specific method (the pointcut). We need to specify when the logic is executed according to the pointcut (e.g., before). The when is the advice. For Spring to intercept the method, the object that defines the intercepted method needs to be a bean in the Spring context. So, the bean becomes the target object of the aspect. Figure 6.2 The aspect terminology. Spring executes some logic (the aspect) when someone calls a specific method (the pointcut). We need to specify when the logic is executed according to the pointcut (e.g., before). The when is the advice. For Spring to intercept the method, the object that defines the intercepted method needs to be a bean in the Spring context. So, the bean becomes the target object of the aspect.

Weaving and Proxy Objects

When Spring intercepts a method call to apply aspect logic, the object must be a bean within the Spring context. However, because the object is an aspect target, Spring does not provide a direct instance reference for the bean. Instead, it provides a proxy object that calls the aspect logic instead of the actual method. This means that whenever you retrieve the bean from the context, either through the getBean() method or dependency injection (DI), you receive the proxy instead of the real bean. This process is known as weaving.