Thursday 26 September 2019

spring boot: Introduction to Aspect

Aspect is a block of code that is injected into application at run time.

In a typical application, application is devided into multiple modules, and each module should handle concerns like logging, security, transactions etc., apart from the business logic.

Aspects are used to solve cross-cutting concerns.

Examples of cross-cutting concerns
a.   Caching
b.   Logging
c.    Transaction Management
d.   Security (Authorization and Authentication)

Key terms in Aspect Oriented Programming
a.   Join Point: It is the line of code that Aspect is going to target (Ex: a method).
b.   Pointcut: It is an expression used to identify the Join Point.
c.    Advice: it is the code that you actually executes at a join point that is selected by Pointcut expression.
d.   Aspect: It is a module that contains all the pointcuts and advices.

Example
@Configuration
@Aspect
public class LoggingAspect {

 @Pointcut("@annotation(com.sample.app.annotations.Loggable)")
 public void executionTimeExpr() {
 }

 @Around("executionTimeExpr()")
 public Object executionTime(ProceedingJoinPoint joinPoint) throws Throwable {
  .....
  .....
  Object result = joinPoint.proceed();
  .....
  .....

  return result;
 }

}

In the above Example,
Aspect: LoggingAspect
Pointcut: executionTimeExpr
Advice: executionTime
JoinPoint: It is the method that matches to given point cut expression.

      Introduction to Aspect
      Aspect: Hello World Application
      Aspects: Before Advice
      Aspect: @After Advice
      Aspects: @Around advice
      Aspect: @Pointcut example


Previous                                                    Next                                                    Home

No comments:

Post a Comment