Spring Boot AOP Introduction

Updated: May 20


Introduction of Spring Boot AOP
Spring Boot AOP Introduction

In this blog, we will get introduced to Aspect-Oriented Programming in Spring Boot Service.


This blog is the second part of the three-part blog series. Here we will get ourself familiarise with Aspect-Oriented Programming with Spring Boot.


Introduction

Introduction

To start with Aspect-Oriented Programming, we have to get ourself familiarise with few terminologies.

  • Cross-Cutting Concerns: All functionalities that are not business logic, categorised as cross-cutting concerns, such as logging, security, exception handling.

  • Advice: Advices are the instruction given to the program to perform the same thing whenever the defined conditions met.

  • Pointcut: It is a condition that we specify so that it executes the advice.

  • Aspect: Aspect it the combination or modularisation of advice given for different cross-cutting concerns.

  • Joinpoint: It is a point during the execution of the program or function.


To get a better understanding of AOP via examples, check out this blog.


Spring Boot uses AOP heavily to enable easy development of services. There are two ways in which we can utilise AOP within our service:

  • With custom annotations (In this, instruction set against any cross-cutting concern will be executed only if we annotate class/ constructor/ property/ functions).

  • Without custom annotations ( It will enable the functionality without adding any code line, considering implementation belongs to the same service. If we have the functionality separated in different spring boot modules, we need to enable auto-configuration).



Type of Advice

Before Advice

Executes before the joinpoint execution.

It will execute before method execution.

Usage

Add @Before annotation to create Before Advice.


Example


After Advice

Executes after the joinpoint execution.

It will execute when the method is completely executed.


Usage

Add @After annotation to create After Advice.


Example


After Return Advice

Executes after joinpoint returns.

It will execute when the method returns.

Usage

Add @AfterReturning annotation to create After Return Advice.


Example


After Throwing Advice

Executes after joinpoint throws an error.

It will execute when a method throws an error.

Usage

Add @AfterThrowing annotation to create After Throwing Advice.


Example


Around Advice

Executes during joinpoint execution.

It will execute during the execution of the method.


Usage

Add @Around annotation to create Around Advice.


Example




I hope this blog helps you to develop an understanding of Aspect-Oriented Programming in Spring Boot.


In my next blog, We will learn about implementing AOP in Spring Boot.


Comments and feedback are most welcomed.


Please follow me on Linkedin, Github, and join our newsletter to keep yourself updated.


Thanks for reading. Happy Learning 😊



282 views

Recent Posts

See All