Sobes.tech
Senior

What are aspects in Spring AOP? What are they used for? Provide examples.

sobes.tech AI

Answer from AI

In Spring AOP (Aspect-Oriented Programming), an aspect is a module that combines cross-cutting concerns such as logging, security, transactions, etc. Aspects allow these concerns to be separated from business logic, improving code readability and maintainability.

An aspect consists of:

  • Advice — code that executes at a specific point (before, after, around a method).
  • Pointcut — an expression that defines which methods the advice applies to.
  • Join point — a point in the program where advice can be applied (e.g., a method call).

Example: logging calls to service methods.

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Method call: " + joinPoint.getSignature().getName());
    }
}

Here, the aspect intercepts all method calls in the com.example.service package and outputs a message before their execution.

Thus, aspects are used to inject additional behavior without modifying the original business logic code.