CodeGym /Courses /Module 5. Spring /How AOP works in Spring: annotations @Aspect, @Around, ...

How AOP works in Spring: annotations @Aspect, @Around, @Before, @After

Module 5. Spring
Level 3, Lesson 3
Available

Annotation @Aspect: entry point into the world of AOP

To get started with AOP in Spring, you need to define an aspect. You use the @Aspect annotation, which tells the Spring container that the class is an aspect. Think of it as a signal: "Hey, Spring, this class has cross-cutting logic — please keep an eye on it!".

Example: creating an aspect Suppose we have a service that performs business operations, and we want to log calls to all its methods:


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component // Register aspect as a Spring Bean
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBeforeMethodCall() {
        System.out.println("Method was called!");
    }
}

What's happening here?

  1. @Aspect: makes this class an aspect.
  2. @Component: lets Spring register the aspect as a bean (without this, @Aspect won't work).
  3. @Before: marks the method that should run before the specified join point.

Fun fact: AOP uses the magic of proxy objects! But don't worry — we'll dive into how that works under the hood soon.


How @Around works

The @Around annotation is the Swiss army knife of AOP. It lets you run logic both before and after a method execution. Even more, you can control whether the method runs at all or modify its result!

Example: measuring method execution time

Let's say we want to measure how long every method call in the service takes:


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PerformanceAspect {

    @Around("execution(* com.example.service.*.*(..))")
    public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        Object result = joinPoint.proceed(); // Execute the target method

        long endTime = System.currentTimeMillis();
        System.out.println("Method " + joinPoint.getSignature() + " executed in "
                           + (endTime - startTime) + " ms");
        return result; // Return the result of the method call
    }
}

What's happening here?

  1. ProceedingJoinPoint: represents the method the aspect is attached to. You can call the method with it or skip it.
  2. proceed(): executes the target method.
  3. Measuring time: we log the difference between timestamps before and after the method call.

When using @Around, remember that calling proceed() is mandatory: without it the target method simply won't run.

Using @Before and @After

If you want to add logic only BEFORE or AFTER a method runs, the @Before and @After annotations are your friends. Let's look at concrete examples.

Example with @Before

Suppose we want to check whether a method belonging to a certain package/class was called:


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthenticationAspect {

    @Before("execution(* com.example.security.*.*(..))")
    public void checkAuthentication() {
        System.out.println("Checking user authentication...");
    }
}

Example with @After

Now let's add some logic that runs AFTER a method call. For example, clear a cache:


import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class CacheAspect {

    @After("execution(* com.example.service.*.*(..))")
    public void clearCache() {
        System.out.println("Clearing cache after method execution...");
    }
}
  • @Before: runs before the method call. Great for input validation, authentication checks, etc.
  • @After: runs after method completion (successful or not). Used for cleanup tasks — closing resources, changing state, etc.

Examples using @Before and @AfterReturning

With @AfterReturning you can get the result of a method and process it:

Example: modifying the return value in @AfterReturning Suppose we want to make sure all strings returned from a method are uppercase:


import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ResultAspect {

    @AfterReturning(pointcut = "execution(String com.example.service.*.*(..))",
                    returning = "result")
    public void modifyReturnValue(String result) {
        System.out.println("Returned result: " + result.toUpperCase());
    }
}

How to configure Pointcut for more flexibility

Most AOP annotations rely on Pointcut expressions. These expressions are the heart of AOP because they indicate which join point to attach to. Here are some examples to make their usage clearer:

Patterns for Pointcut:

  1. execution(* com.example.service.*.*(..)):
    • All methods in the com.example.service packages.
  2. execution(public * *(..)):
    • All public methods in all classes.
  3. execution(* com.example..*.*(..)):
    • Any method in any class located under the com.example package.
  4. @annotation(org.springframework.transaction.annotation.Transactional):
    • Apply the aspect to all methods annotated with @Transactional.

Limitations and common pitfalls

  1. Won't work without Spring AOP: make sure the aspect is enabled via configuration (for example, with @EnableAspectJAutoProxy in your configuration class).
  2. Errors in Pointcut expressions: if the join points don't match your definition, the aspect won't run.
  3. Performance issues: using AOP can slow down method execution (especially with heavy logging).
  4. Proxy objects: remember that AOP works via proxies (you need Spring beans).

What's next?

Now you know how to use the @Aspect, @Around, @Before, and @After annotations to create powerful and flexible aspects in Spring. These tools make it easy to add cross-cutting logic to your app, keeping your code cleaner and more modular.

The next steps are putting this into practice: crafting complex Pointcut expressions and building custom aspects.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION