eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

We often use logging to document meaningful steps and valuable information during the program execution. It allows us to record data we can use later to debug and analyze the code.

Additionally, Aspect-Oriented Programming (or AOP for short) is a paradigm that lets us segregate cross-cutting concerns, such as transaction management or logging, throughout the application without cluttering the business logic.

In this tutorial, we’ll learn how to implement logging using the AOP and Spring framework.

2. Logging Without AOP

When it comes to logging, we usually put logs at the beginning and the end of the methods. This way, we can easily track the application execution flow. In addition, we can capture the values being passed to specific methods and the values they return.

To demonstrate, let’s create the GreetingService class with the greet() method:

public String greet(String name) {
    logger.debug(">> greet() - {}", name);
    String result = String.format("Hello %s", name);
    logger.debug("<< greet() - {}", result);
    return result;
}

Even though the implementation above seems like a standard solution, logging statements can feel like unnecessary clutter in our code.

Furthermore, we introduced additional complexity to our code. Without logging, we could rewrite this method as a one-liner:

public String greet(String name) {
    return String.format("Hello %s", name);
}

3. Aspect-Oriented Programming

As the name suggests, Aspect-Oriented Programming focuses on aspects rather than objects and classes. We use AOP to implement additional functionality for specific application parts without modifying their current implementations.

3.1. AOP Concepts

Before we dive in, let’s examine the basic AOP concepts at a very high level.

  • Aspect: The cross-cutting concern or the functionality we’d like to apply throughout the application.
  • Join Point: The point of the application flow where we want to apply an aspect.
  • Advice: The action that should be executed at a specific join point.
  • Pointcut: Collection of join points where an aspect should be applied.

Furthermore, it’s worth noting that Spring AOP only supports join points for method execution. We should consider using compile-time libraries such as AspectJ to create aspects for fields, constructors, static initializers, etc.

3.2. Maven Dependency

To use Spring AOP, let’s add the spring-boot-starter-aop dependency in our pom.xml:

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

4. Logging With AOP

One way to implement AOP in Spring is by using a Spring bean annotated with the @Aspect annotation:

@Aspect
@Component
public class LoggingAspect {
}

The @Aspect annotation serves as a marker annotation, so Spring won’t automatically treat it as a component. To indicate it should be a bean managed by Spring and detected through component scanning, we also annotate the class with the @Component annotation.

Next, let’s define a pointcut. Simply put, pointcuts allow us to specify which join point execution we want to intercept with an aspect:

@Pointcut("execution(public * com.baeldung.logging.*.*(..))")
private void publicMethodsFromLoggingPackage() {
}

Here, we defined a pointcut expression that includes only public methods from the com.baeldung.logging package.

Moving forward, let’s see how to define the advice to log the start and the end of the method execution.

4.1. Using Around Advice

We’ll start with the more general advice type – the Around advice. It allows us to implement custom behavior before and after the method invocation. Moreover, with this advice, we can decide whether to proceed with the specific join point, return a custom result, or throw an exception.

Let’s define the advice using the @Around annotation:

@Around(value = "publicMethodsFromLoggingPackage()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    String methodName = joinPoint.getSignature().getName();
    logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
    Object result = joinPoint.proceed();
    logger.debug("<< {}() - {}", methodName, result);
    return result;
}

The value attribute associates this Around advice with the previously defined pointcut. The advice runs around method executions matched by the publicMethodsFromLoggingPackage() pointcut signature.

The method accepts a ProceedingJoinPoint parameter. It’s a subclass of the JoinPoint class, allowing us to call the proceed() method to execute the next advice (if it exists) or the target method.

We call the getArgs() method on the joinPoint to retrieve the array of method arguments. Additionally, we use the getSignature().getName() method to get the name of the method we’re intercepting.

Next, we call the proceed() method to execute the target method and retrieve the result.

Finally, let’s call the greet() method we mentioned earlier:

@Test
void givenName_whenGreet_thenReturnCorrectResult() {
    String result = greetingService.greet("Baeldung");
    assertNotNull(result);
    assertEquals("Hello Baeldung", result);
}

After running our test, we can see the following result in our console:

>> greet() - [Baeldung]
<< greet() - Hello Baeldung

5. Using the Least Invasive Advice

When deciding which type of advice to use, it’s recommended that we use the least powerful advice that serves our needs. If we choose a general advice, such as Around advice, we’re more prone to potential errors and performance issues.

That’s to say, let’s examine how to accomplish the same functionality, but this time using the Before and After advices. Unlike Around advice, they don’t wrap the method execution, thus, there’s no need to explicitly call the proceed() method to continue with join point execution. Specifically, we use these types of advice to intercept methods right before or after execution.

5.1. Using Before Advice

To intercept the method before its execution, we’ll create an advice using the @Before annotation:

@Before(value = "publicMethodsFromLoggingPackage()")
public void logBefore(JoinPoint joinPoint) {
    Object[] args = joinPoint.getArgs();
    String methodName = joinPoint.getSignature().getName();
    logger.debug(">> {}() - {}", methodName, Arrays.toString(args));
}

Similar to the previous example, we used the getArgs() method to get method arguments and the getSignature().getName() method to get the method name.

5.2. Using AfterReturning Advice

Going further, to add a log after the method execution, we’ll create the @AfterReturning advice that runs if a method execution completes without throwing any exception:

@AfterReturning(value = "publicMethodsFromLoggingPackage()", returning = "result")
public void logAfter(JoinPoint joinPoint, Object result) {
    String methodName = joinPoint.getSignature().getName();
    logger.debug("<< {}() - {}", methodName, result);
}

Here, we defined the returning attribute to get the value returned from the method. Additionally, the value we provided in the attribute should match the parameter’s name. The return value will be passed to the advice method as an argument.

5.3. Using AfterThrowing Advice

On the other hand, to log situations when the method invocation completes with an exception, we could use the @AfterThrowing advice:

@AfterThrowing(pointcut = "publicMethodsFromLoggingPackage()", throwing = "exception")
public void logException(JoinPoint joinPoint, Throwable exception) {
    String methodName = joinPoint.getSignature().getName();
    logger.error("<< {}() - {}", methodName, exception.getMessage());
}

This time, instead of the return value, we’ll get the thrown exception in our advice method.

6. Spring AOP Pitfalls

Lastly, let’s discuss some concerns we should consider when working with Spring AOP.

Spring AOP is a proxy-based framework. It creates proxy objects to intercept method calls and apply logic defined in advice. This can negatively impact the performance of our application.

To reduce the effect of AOP on performance, we should consider using AOP only when necessary. We should avoid creating aspects for isolated and infrequent operations.

Finally, if we use AOP for development purposes only, we can create it conditionally, for instance, only if a specific Spring profile is active.

7. Conclusion

In this article, we learned how to perform logging using Spring AOP.

To sum up, we examined how to implement logging using Around advice as well as Before and After advice. We also explored why it’s important to use the least powerful advice to fit our needs. Finally, we addressed some potential issues Spring AOP brings to the table.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI – (cat=Spring)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments