Internal Developer Portals are reshaping the developer experience. What's the best way to get started? Do you build or buy? Tune in to see.

Agentic AI. It's everywhere. But what does that mean for developers? Learn to leverage agentic AI to improve efficiency and innovation.

Modernize enterprise Java apps. Learn to enhance generative AI capabilities across Jakarta EE and Spring Boot platforms.

For Java apps, containerization helps solve the majority of challenges related to portability and consistency. See how.

Implementing AOP With Spring Boot and AspectJ

Aspect-Oriented Programming can be tricky for some. In this post, we take a look at an example of how you can implement AOP in Spring Boot by making use of AspectJ.

By  · Tutorial
Comment (1)
Save
209.4K Views

This guide will help you implement AOP with Spring Boot Starter AOP. We will implement four different advices using AspectJ and also create a custom annotation to track execution time of a method.

You Will Learn

  • What are cross-cutting concerns?
  • How do you implement cross-cutting concerns in an application?
    • If you want to log every request to a web application, what are the options you can think of?
    • If you want to track the performance of every request, what options can you think of?
  • What are Aspects and Pointcuts in AOP?
  • What are the different types of AOP advices?
  • How do you implement AOP with Spring Boot?
  • How can you use Spring AOP and AspectJ to implement your aspects?
  • What are some AOP best practices?

Project Code Structure

The following screenshot shows the structure of the project we will create.Image

A few details:

  • SpringBootTutorialBasicsApplication.java: The Spring Boot application class generated with Spring Initializer. This class acts as the launching point for the application.
  • pom.xml: Contains all the dependencies needed to build this project. We will use Spring Boot Starter AOP.
  • Business1.java, Business2.java, Dao1.java, Dao2.java: Business classes are dependent on DAO classes. We would write aspects to intercept calls to these business and DAO classes.
  • AfterAopAspect.java: Implements a few After advices.
  • UserAccessAspect.java: Implements a Before advice to do an access check.
  • BusinessAopSpringBootTest.java: The unit test that invokes the business methods.
  • Maven 3.0+ is your build tool
  • Your favorite IDE. We use Eclipse.
  • JDK 1.8+

Complete Maven Project With Code Examples

Our GitHub repository has all the code examples

Introduction to AOP

Applications are generally developed with multiple layers. A typical Java application has:

  • Web Layer: Exposing services to the outside world using REST or a web application
  • Business Layer: Business logic
  • Data Layer: Persistence logic

While the responsibilities of each of these layers are different, there are a few common aspects that apply to all layers

  • Logging
  • Security

These common aspects are called cross-cutting concerns.

One option of implementing cross-cutting concerns is to implement them separately in every layer. However, that would make the code difficult to maintain.

Aspect Oriented Programming provides a solution for implementing cross-cutting concerns.

  • Implement the cross-cutting concern as an aspect.
  • Define pointcuts to indicate where the aspect has to be applied.

This ensures that the cross-cutting concerns are defined in one cohesive code component and can be applied as needed.

Setting up Spring Boot AOP Project

Creating a Spring AOP Project with Spring Initializr is a cake walk.

Spring Initializr (http://start.spring.io/) is great tool to bootstrap your Spring Boot projects.

Notes:

  • Launch Spring Initializr and choose the following
    • Choose com.in28minutes.springboot.tutorial.basics.example as Group
    • Choose spring-boot-tutorial-basics as Artifact
    • Choose the following Dependencies
      • AOP
  • Click Generate Project.
  • Import the project into Eclipse.

Spring Boot AOP Starter

The key dependencies in the Spring Boot AOP Starter are:

  • Spring AOP provides basic AOP Capabilities.
  • AspectJ provides a complete AOP framework.

Setting Up AOP

Let’s add a couple of business classes — Business1 and Business2. These business classes are dependent on a couple of data classes — Data1 and Data2.





Notes:

  • @Autowired private Dao1 dao1: The DAOs are autowired as dependencies into the Business classes.
  • public String calculateSomething(){: Each of the business classes has a simple calculate method.

A Simple AOP Unit Test

Let’s write a simple unit test to invoke the business classes we've created:


Notes:

  • @RunWith(SpringRunner.class)
    @SpringBootTest public class BusinessAopSpringBootTest
    : We are launching the complete Spring Boot application in the unit test.
  • @Autowired private Business1 business1 and @Autowiredprivate Business2 business2: Autowire the business classes into the test from the launched Spring Context.
  • @Test public void invokeAOPStuff() {: Invoke the methods on the business services.

At this point, we have no AOP logic implemented. So, the output would be the simple messages from the Dao and Business classes.


Implementing the @Before Advice

Typically, when we implement security using AOP, we would want to intercept the call to the method and apply your check. This is typically done using the @Before advice.

An implementation is shown below:


Notes

  • @Aspect: indicates that this is an Aspect
  • @Configuration: indicates that this file contains a Spring Bean Configuration for an Aspect.
  • @Before : We would want to execute the Aspect before the execution of the method
  • ("execution(* com.in28minutes.springboot.tutorial.basics.
    example.aop.data.*.*(..))"
    : This defines the pointcut. We would want to intercept all method calls made to any methods in package com.in28minutes.springboot.tutorial.basics.example.aop.data

When you run the unit test, you will see that, before executing the DAO method, the user access check code is executed:


Understanding AOP Terminology: Pointcut, Advice, Aspect, Join Point

Let’s spend some time understanding the AOP terminology.

  • Pointcut: the expression used to define when a call to a method should be intercepted. In the above example, execution(* com.in28minutes.springboot.tutorial.basics.
    example.aop.data.*.*(..))
    is the pointcut.
  • Advice: What do you want to do? An advice is the logic that you want to invoke when you intercept a method. In the above example, it is the code inside the before(JoinPoint joinPoint) method.
  • Aspect: A combination of defining when you want to intercept a method call (Pointcut) and what to do (Advice) is called an Aspect.
  • Join Point: When the code is executed and the condition for pointcut is met, the advice is executed. The Join Point is a specific execution instance of an advice.
  • Weaver: Weaver is the framework that implements AOP — AspectJ or Spring AOP.

Using the @After, @AfterReturning, and @AfterThrowing Advices

Let’s now the other interception options AOP provides.

  • @After: executed in two situations — when a method executes successfully or it throws an exception.
  • @AfterReturning: executed only when a method executes successfully.
  • @AfterThrowing: executed only when a method throws an exception.

Let’s create a simple Aspect with a couple of these variations.


The code is self-explanatory.

The output from execution is shown below:



As you can see, just before returning the values to the calling business methods, the after advices are executed.

Other AOP Features: @Around and Annotations

One of the other features you can implement using AOP are custom annotations for intercepting method calls.

The example below shows a simple TrackTime annotation:


We can add an Aspect defining what should be done when the TrackTime annotation is used. MethodExecutionCalculationAspect implements a simple time tracking:


Notes:

  • @Around uses an around advice. It intercepts the method call and uses joinPoint.proceed() to execute the method.
  • @annotation(com.in28minutes.springboot.tutorial.basics.example.aop.TrackTime) is the pointcut to define interception based on an annotation — @annotation followed by the complete type name of the annotation.

Once we define the annotation and the advice, we can use the annotation on methods that we would want to track, as shown below:


AOP Best Practices

One AOP best practice is to define a common class to store all the pointcuts. This helps in maintaining the pointcuts in one place.


The above common definition can be used when defining pointcuts in other aspects.


Complete Code Examples

pom.xml



/src/main/java/com/in28minutes/springboot/tutorial/basics/example/aop/AfterAopAspect.java



/src/main/java/com/in28minutes/springboot/tutorial/basics/example/aop/business/Business1.java



/src/main/java/com/in28minutes/springboot/tutorial/basics/example/aop/business/Business2.java



/src/main/java/com/in28minutes/springboot/tutorial/basics/example/aop/data/Dao1.java



/src/main/java/com/in28minutes/springboot/tutorial/basics/example/aop/data/Dao2.java



/src/main/java/com/in28minutes/springboot/tutorial/basics/example/aop/UserAccessAspect.java


/src/main/java/com/in28minutes/springboot/tutorial/basics/example/SpringBootTutorialBasicsApplication.java



/src/test/java/com/in28minutes/springboot/tutorial/basics/example/aop/BusinessAopSpringBootTest.java



/src/test/java/com/in28minutes/springboot/tutorial/basics/example/SpringBootTutorialBasicsApplicationTests.java

Published at DZone with permission of Ranga Karanam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Comments