Sitemap
FAUN.dev() 🐾

We help developers learn and grow by keeping them up with what matters. 👉 www.faun.dev

Aspect-Oriented Programming in Java

4 min readSep 12, 2023

--

Unlocking the Power of Aspect-Oriented Programming for Enhanced Java Applications

Summary

Explore Aspect-Oriented Programming (AOP) with AspectJ in Java. This article introduces AOP concepts, demonstrates AOP integration with Spring, and covers various advice types and joinpoints. Learn to enhance method behavior and handle common errors in AOP. Implement some basic demonstrations to understand what aspect-oriented programming does and then try to dive deep into AspectJ.

Key Concepts in AOP

There are 3 main terms in the Spring AOP. We will understand what they are when we are having a demonstration now, even so here are brief descriptions of them.

  • Pointcut: Defines where to apply advice.
  • Joinpoint: A specific execution point.
  • Advice: Code executed at a joinpoint.

Let's see a quick example then we can examine the terms particularly.

Demonstration

We will use the spring’s AOP dependency because it's much easier to configure if you have a spring boot project.

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

For the first step, let's create a simple service class with a method to test our aspect.

@Service
public class MyService {
public void run() {
System.out.println(“***Method called”);
}
}

Now we will create our aspect class which can contain our main components; pointcut, joinpoint, and advice. Then add a method with @Before advice and execution joinpoint for now. Then we will see a proper message logged before the method call.

import org.aspectj.lang.annotation.Aspect;

@Aspect
@Service
public class MyAspect {
@Before("execution(* run(..))")
public void beforeAdviceWithExecutionJoinPoint() {
System.out.println("Before method called");
}
}

Output:

Before method called
***Method called

Get Emin Bilgic’s stories in your inbox

Join Medium for free to get updates from this writer.

@Pointcut(“execution(* run(..))”)
public void executionPointcut() {}

@Before("executionPointcut()")
public void beforeAdviceWithExecutionPointcut() {
System.out.println(" Before method called");
}

Here is a pretty simple example without using any @Pointcut, and it will create the same output as the example above. You can achieve most of the things without using pointcuts. But maintains your aspect class’s structure and allows you to manage your advice flexibly.

Deeper Understanding of Advices

Here we explore how to use various advice types, including @Around, @Before, @After, @AfterReturning, and @AfterThrowing, to intercept and enhance the behavior of methods defined by executionPointcut() our Spring application. Gain insights into method execution flow control.

@Around("executionPointcut()")
public Object aroundAdviceWithExecutionPointcut(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println(" Around method called (before)");
Object proceed = joinPoint.proceed(); // this is the actual method call
System.out.println(" Around method called (after)");
return proceed;
}

@Before(“executionPointcut()”)
public void beforeAdviceWithExecutionPointcut() {
System.out.println(“ Before method called”);
}

@After(“executionPointcut()”)
public void afterAdviceWithExecutionPointcut() {
System.out.println(“ After method called”);
}

@AfterReturning(“executionPointcut()”)
public void afterReturningAdviceWithExecutionPointcut() {
System.out.println(“ After returning method called”);
}

//Works only if the method throws an exception
@AfterThrowing(“executionPointcut()”)
public void afterThrowingAdviceWithExecutionPointcut() {
System.out.println(“ After throwing method called”);
}

Here is the output:

Around method called before
Before method called
***Method called
After returning method called
After method called
Around method called after

A frequently occurred error during my research

Because I encountered this interesting error when having demonstrations on Aspect Oriented Programming, I would like to explain it here. The error is thrown by the code generation library (CGLIB) that is used by the Spring:

Could not generate CGLIB subclass of class org.springframework.boot.autoconfigure.AutoConfigurationPackages$BasePackages: Common causes of this problem include using a final class or a non-visible class.

Actually, there is a huge hint, the error log tells us we are trying to touch final or non-visible classes. So basically reason this error is because of the broad scope of one of the joinpoints. An example malformed joinpoint code is:

@Before(“execution(* *(..))”)
public void beforeAdvice() {
System.out.println(“Before method called”);
}

Even if you narrow the scope to the main module of your project will fix this issue:

@Before(“execution(* com.example.springaspects..*(..))”)

Conclusion

In conclusion, Aspect-Oriented Programming with AspectJ offers powerful tools to enhance Java applications. Understanding AOP concepts, integrating them with Spring, and mastering advice types and joinpoints can significantly improve code modularity and maintainability. Be mindful of common errors and adopt AOP judiciously to unlock its full potential in your projects.

👋 If you find this helpful, please click the clap 👏 button below a few times to show your support for the author 👇

🚀Join FAUN Developer Community & Get Similar Stories in your Inbox Each Week

--

--

FAUN.dev() 🐾
FAUN.dev() 🐾

We help developers learn and grow by keeping them up with what matters. 👉 www.faun.dev