AspectJ

To code in Aspect-oriented design which dynamically execute one piece of code before or after or during another function.

A few terms

  • aspect: Involves advice, join point, point cut, … . Basically one aspect means the component to control the whole flow from start to end
  • advice: The code in aspect that designs to run at a point
  • join point: A specific point which the advice can run on
  • join cut: Group of join point where the advice is applied to
  • weaving: The process of integrating aspect to the program

Use cases:

  • Logging
  • Caching
  • Exception handling
  • Transaction Management
  • Performance monitoring

Example

@Aspect
@Component
@Slf4j
public class MyAspect {
  @Around("execution(public * *.services.CustomerService.*(..))")
  public Object logMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    System.out.println("called method");
    return proceedingJoinPoint.proceed(proceedingJoinPoint.getArgs());
  }
}

This basically print "called method" for every single method inside CustomerService class

SpringBoot Integration

In SpringBoot, you can enable @EnableAspectJAutoProxy so that you can register the aspect as a bean

For example:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
    // Your other configuration here
}

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

@Aspect
@Component
public class MyAnnotationAspect {

    @Before("@annotation(com.example.MyAnnotation)")
    public void beforeRegisterCustomer() {
        // Add your logic here that runs before the annotated method
        System.out.println("Before registering the customer");
    }
}
@MyAnnotation
public void registerCustomer() {
    System.out.println("Registered the customer");
}