Spring AOP

In your application you can have certain operations like transaction management, logging or security across different modules. This could create code redundancy across your application. We call these redundant operations that span across modules as cross-cutting concerns.

For example, consider an application that needs to log parameters of method calls and the method execution time for debugging purposes. Instead of inserting a repeated logging code across methods, you can use AOP offered by the Spring framework.

Before implementing this, we need to be familiar with a few basic concepts. 

Basic Concepts

Aspect: It is a simple POJO class. It contains the common logic that is applicable across modules. We use @Aspect annotation to mark an aspect.

@Aspect
@Component
public class ExectionInfoAspect {

}

The above code will declare ExectionInfoAspect as an aspect.

Advice: This indicates when and where an aspect needs to be invoked. Few common advice types are – around, before and after. Before advice allows you to perform some processing before a method executes. After advice is executed after a method completes. Around advice is executed before and after a method invocation.

@Around
public Object logExecutionInfo(ProceedingJoinPoint joinPoint) {
    // do something before method execution
    Object proceed = joinPoint.proceed();
    // do something after method execution
    return proceed;
}

Point cut: Point cuts are expressions or patterns that specify where an aspect is to be executed.

@Around("@annotation(ExecutionInfo)")
public Object logExecutionInfo(ProceedingJoinPoint joinPoint) {
    // do something before method execution
    Object proceed = joinPoint.proceed();
    // do something after method execution
    return proceed;
}

In the example above we have provided a point cut argument to the advice to indicate Apply this advice to any method that is annotated with @ExecutionInfo annotation.

As we are now familiar with the basic concepts, let’s see it in action.

Sample implementation

First of all declare dependency for Spring AOP module in pom.xml file.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.3.21</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.11</version>
</dependency>

Now create an annotation called ExecutionInfo which will be applicable on methods.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExecutionInfo {

}

Create an aspect with advice.

@Aspect
@Component
public class ExectionInfoAspect {
    @Around("@annotation(ExecutionInfo)")
    public Object logExecutionInfo(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String arguments = Arrays.toString(joinPoint.getArgs());
        System.out.println(joinPoint.getSignature() + " args: " + arguments);
        Object proceed = joinPoint.proceed();
        long executionTime = System.currentTimeMillis() - startTime;
        System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    }
}

Now create a bean with a method annotated with @ExecutionInfo annotation.

@Service
public class Vehicle {
    @ExecutionInfo
    public void sampleMethod(long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Enable AOP in configuration class.

@EnableAspectJAutoProxy
@Configuration
public class AppConfig {

}

Finally test the implementation.

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
Vehicle vehicle = applicationContext.getBean(Vehicle.class);
vehicle.sampleMethod(500);

It will print following output –

void com.kcs.service.Vehicle.sampleMethod(long) args: [500]
void com.kcs.service.Vehicle.sampleMethod(long) executed in 533ms

Now we are done and we are getting output exactly what we wanted.

That’s it for now. Hope you have enjoyed this tutorial. If you have any doubt, please ask in the comment section. I will try to answer that as soon as possible. Till then, bye bye.

One thought on “Spring AOP

  1. Itís nearly impossible to find experienced people on this subject, but you sound like you know what youíre talking about! Thanks

Comments are closed.