Spring - AOP

springmvc

https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations

// Spring AOP

Maven dependencies:

spring-aop
spring-aspects
aspectjweaver

Functionality spanning multiple layers of applications are called cross cutting 
concerns. Examples are logging, security, declaration, transactions. Cross 
cutting concerns are best implemented using Aspect Oriented Programming (AOP). 
AOP enables us to apply the cross cutting features across multiple classes.

For example, if we want to track all the method calls in your application, like 
each time that a method is invoked, we want to log the fact that the method was 
invoked with the parameters that it was invoked with. In the old way, we whould 
have to to modify the code to add the logger statement to each class and method. 
With aspect oriented programming, we can specify the methods that we want to 
track without having to modify the method.

Aspect: is an aspect of a concern. An Aspect is the code that you want to execute.
PointCut: the selection criteria.
JoinPoint: this is a class of the object that give more information.
Advice: action taken by an aspect at a particular join point
Weaving: linking aspects with other application types or object to create

@Aspect
public class LoggingAspect {
  @Before("execution(* com.companyName.service.*.get*())")
  public void getAllAdvice() {
    System.out.println("Service method");
  }
}

In the above code, the @Aspect annotation indicates that this is an aspect.
The thing that goes inside the @Before annotation is a PointCut. This specifies
that the getAllAdvice method should be execute before any methods that the
name starts with get and is inside the com.companyName.service.* packages.

@Aspect
@Component
class MyAspect {
  @Before("execution(* com.companyName.HiByeService.*(..))")
  public void before(JoinPoint joinPoint) {
    System.out.print("Before ");
    System.out.println(joinPoint.getSignature().getName());
    System.out.println(Arrays.toString(joinPoint.getArgs()));
  }
  @AfterReturning(pointcut = "execution(* com.companyName.HiByeService.*(..))",
    returning="result")
  public void after(JoinPoint joinPoint, Object result) {
    System.out.print(joinPoint.getSignature().getName());
    System.out.print(" result is " + result);
  }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(class = SpringContextAOP.class)
public class AOPExampleTest {
  @Autowired
  private HiByeService service;
  @Test
  public void testSomething() {
    service.sayHi();
    service.sayBye();
  }
}

The above code is run with JUnit.  It use a service class that offer the sayHi
and the sayBye method.  The name of the class (MyAspect) does not matter.  
Inside this class, we have the @Before annotation and the @AfterReturning
annotation.  The PointCut inside these annotation select the methods that this
code is applicable to.  The name of the methods (before, and after) does not 
matter.  The parameter to the before method is a JoinPoint. We can use this 
object to get more information about the method that is intercepted.  For 
example, we can get the name, signature, and arguments that was passed to
the intercepted method.  The @AfterReturning annotation allows us to retrieve
the return result of the intercepted method.

AOP Advices:

1. Before advice: Executed before executing the actual method
2. After returning advice: Executed after executing the actual method
3. After throwing advice: Executed if the actual method throws an exception
4. After (finally) advice: Executed in all scenarios (exception or not) after 
   actual method call.
5. Around advice: Most powerful advice which can perform custom behavior before 
   and after the method invocation.

Spring AOP can only be used with components that are managed by Spring.
If the component is not managed by Spring, we can use another AOP framework 
such as AspectJ.

Spring AOP can only intercept something simple such as method calls. If you 
need to intercept something more complicate than that, you probably should 
go for an AOP framework such as AspectJ. For example, if you need to 
intercept when the value of a variable is changed. That is something that 
AspectJ can intercept.

What are cross cutting concerns?

Functionality spanning multiple layers of applications are called cross cutting concerns. Examples are logging, security, declaration, transactions.

How does Aspect Oriented Programming implements cross cutting concerns?

Cross cutting concerns are best implemented using Aspect Oriented Programming (AOP). AOP enables us to apply the cross cutting features across multiple classes.

For example, if we want to track all the method calls in your application, like each time that a method is invoked, we want to log the fact that the method was invoked with the parameters that it was invoked with. In the old way, we whould have to to modify the code to add the logger statement to each class and method. With aspect oriented programming, we can specify the methods that we want to track without having to modify the method.

What is an Aspect?

An Aspect is an aspect of a concern. An Aspect is the code that you want to execute.

What is a PointCut in AOP?

It is the selection criteria.

How can we implement AOP for logging and exception handling?

//*.save*
//*.get*
//*BOImpl.get*

// Logger.logMsg(Logger.INFO, methodName + methodParams)
@Aspect
public class LoggingAspect {

  @Before("execution(* com.rithus.service.*.get*())")
  public void getAllAdvice() {
    System.out.println("Service method");
  }
}
@Aspect
@Component
class MyAspect {
  @Before("execution(* com.companyName.HiByeService.*(..))")
  public void before(JoinPoint joinPoint) {
    System.out.print("Before ");
    System.out.println(joinPoint.getSignature().getName());
    System.out.println(Arrays.toString(joinPoint.getArgs()));
  }

  @AfterReturning(pointcut = "execution(* com.companyName.HiByeService.*(..))",
    returning="result")
  public void after(JoinPoint joinPoint, Object result) {
    System.out.print(joinPoint.getSignature().getName());
    System.out.print(" result is " + result);
  }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(class = SpringContextAOP.class)
public class AOPExampleTest {
  @Autowired
  private HiByeService service;

  @Test
  public void testSomething() {
    service.sayHi();
    service.sayBye();
  }
}

What are different types of AOP advices?

  1. Before advice: Executed before executing the actual method
  2. After returning advice: Executed after executing the actual method
  3. After throwing advice: Executed if the actual method throws an exception
  4. After (finally) advice: Executed in all scenarios (exception or not) after actual method call.
  5. Around advice: Most powerful advice which can perform custom behavior before and after the method invocation.

What are the two options for Aspect Oriented Programming with Spring MVC?

  1. Spring AOP can only be used with components that are managed by Spring
  2. If the component is not managed by Spring, we can use another AOP framework such as AspectJ.

What are the limitation with Spring AOP?

  1. Spring AOP cannot be used on components that are not managed by Spring.
  2. Spring AOP can only intercept something simple such as method calls. If you need to intercept something more complicate than that, you probably should go for an AOP framework such as AspectJ. For example, if you need to intercept when the value of a variable is changed. That is something that AspectJ can intercept.

What are the dependencies that we need to add in order to use Spring AOP?

spring-aop
spring-aspects
aspectjweaver

What are the terminologies used in Aspect Oriented Programming?

  1. Aspect: A concern
  2. Pointcut: An expression which determines what are the methods that the Advice
  3. Join point: a point douring the execution of a program such as the execution
  4. Advice: action taken by an aspect at a particular join point
  5. Weaving: linking aspects with other application types or object to create
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License