Software Development, Spring

Spring Framework Basic AOP Example

AOP is one of those things in the Spring Framework that we might not need, even for basic implementation, which we have an example for in this post. But we should always consider using Spring AOP whenever possible to have a modular and maintainable application. The benefit we could reap is enormous. Of course, it depends on the type of project we work on. Sadly, not many people (even experienced ones) appreciate the benefits of separating cross-cutting concerns. They would instead code away without maintainability in mind. If they implemented some modularity, it would be in some form of experimental feature (for sport).

This post shows how to use basic Spring Framework AOP (still without Spring Boot).

Minimum Dependency For Spring AOP

To get us started with our AOP example, we need a Spring project that works for AOP – particularly the dependencies it needs. At a minimum, we would require the following dependencies in our pom.xml file.

We do not have a lot of dependencies for our basic Spring AOP example, do we? Nope! We only need the spring-context, and Maven will take the rest of the transitive core dependencies. Thus, we only have two AOP-related dependencies, which are spring-aop and spring-aspects. These dependencies have other dependencies which Maven will take care of. These dependencies are enough to get us going.

Service Bean To Use AOP On

We need a test subject for our basic Spring AOP example, and we can use a service bean! Typically,  we annotate this type of bean with @Service. Thus, a service bean. Furthermore, it has six methods (our target join points), but we will only test five using our basic Spring AOP example.

The method createPersonForAOAround is for another post.

The Aspect For Our AOP Example

Before we proceed, here are some terms we need to familiarize with – Aspect, Pointcut, and Advice. First, an Aspect is a class we annotate with @Aspect and @Component (or its derivatives). We use its codes to “extend” our service bean (PersonService) methods. Second, we have Pointcuts. They specify which join points in PersonService we map various “extending” codes to. We typically use the annotations @Before, @After, @AfterThrowing, @AfterReturning, and @Around to specify the pointcuts in the form of expressions. Finally, we have Advice which is the action our codes (plus the semantics of those AOP annotations) perform at those join points.

Then, we test our basic Spring AOP example by invoking those service methods from the main method.

When we run the codes, we get the following output.

For more information about the codes, please get them from our Turreta GitHub repository.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like