What is Aspect Oriented Programming? — Spring AOP

Mehmet Demircan
3 min readJun 29, 2022

Hello everyone, you may use this guide to get a simple and practical understanding of how Spring’s AOP component. I will talk about AOP as far as I know. In addition, I will develop an application example about Spring AOP.

What is Cross Cutting Concern?

Concern is an abstract structure used in some parts of our apps such as logging, performance, transaction management, security, caching, validation, exception handling. Cross cutting concern can be used anywhere in our apps.

What is Aspect Oriented Programming?

Aspect is a programming paradigm to implement cross cutting concern and its starting point of paradigm is to produce solutions to concerns. The motivation using this structure, it conforms with principles such as single responsibility and don’t repeat yourself.

What are benefits?
- More flexible and easy management of our apps.
- Non-repeating codes.
- Clean and easy to understand codes.
- Separation of core logic and concerns.

Some examples from daily life:
Logging → Logging requests and responses to come to the controller.
Transaction Management → Refund process after error occurring in running code cycle since the receipt of payment.
Performance → Calculating method execution time.
Validation → Check email allow status of user before sending email.

If you are still interested, let’s talk about technique.
Let’s start add AOP dependency of Spring to pom.xml:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Advice Types

@Before: It will run before the method.
@AfterReturning: If the method is successful, it will run after the method.
@AfterThrowing: If an exception occurs in the method, it will run.
@After: It will run after returning or throwing. (finally)
@Around: It will run firstly before the method and secondly after the method.

Pointcut Expressions

It determines which should match our pointcut and aspect.

target: It refers to targeted bean.
execution: It uses where the method will run is specified.
@target: It uses annotation if it has annotated any process.

There are a lot of working method for pointcut, you can also review different working methods in the resources section.
Example for performance logging app:

You should use JoinPoint like below:

@Before, @After, @AfterReturning, @AfterThrowing

You should use ProceedingJoinPoint like beloew:
The difference from JointPoint, you can handle return value with .proceed().

@Around

Our logs after get all emails:

You can reach source codes and more examples here.
I told what I know, I hope it was useful. :)

Sources

--

--