Spring AOP @After advice with Examples

This article provides detailed Introduction and practical examples of Using Spring AOP @After advice in a Spring or Spring Boot Application.

Spring AOP After Advice Introduction

Aspect Oriented Programming is a generic concept and there are a plenty of AOP frameworks in the market. However, this post is limited to After Advice in Spring or Spring Boot.

An After advice runs after the target method is finished, including when the target method results in exception. This advice is similar to the finally block in Java that it always executes irrespective of the outcome.

We can use After advice for the purpose of logging, or resource cleanups.

Spring AOP After Advice Setup

In this section, we will setup all the essential components before before writing an example of After advice. Let’s begin with dependencies.

Dependency

In order to use Spring AOP we need to add dependency for spring-aspects library. Make sure to use the latest version.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>{spring.aop.version}</version>
</dependency>Code language: HTML, XML (xml)

Enable Spring Aspects

If we are developing a Spring Application, we need to enable Aspect Oriented Programming module explicitly. To do this, we can use @EnableAspectJProxy annotation on the configuration class.

@Configuration
@EnableAspectJAutoProxy
public class ApplicationConfig {
    ....Code language: Java (java)

For a Spring Boot application the auto configuration automatically enables the module when it finds the dependency on the class path.

Target Class

We can use any normal Java class as a target. We only need to make it a Spring Bean by putting any stereotype annotation. For our examples, we will use the next class that has one method.

@Service
public class FileSystemStorageService {
    public List<String> readFile(String name) {
        log.info("Reading file: {}", name);
        // Skipped
        return List.of("Text from file");
    }
}Code language: Java (java)

Example Spring AOP After Advice

To create an advice, we need to create an Aspect class. An aspect class is any normal Java class annotated with @Aspect. In the aspect class, we can write an advice method and annotate it with @After annotation.

We also need to provide Pointcut expression, that matches the intended join points, which in our case is the target method.

Next, is an Example of Spring AOP After advice.

@Slf4j
@Aspect
@Component
public class LoggingAspect {
    @After("execution(* com.amitph.spring.aop.service.FileSystemStorageService.readFile(..)) ")
    public void logAfterMethodCall() {
        log.info("After Executing target");
    }
}Code language: Java (java)

Our advice is mapped to any readFile method from the FileSystemStorageService class. Now, we will try to execute the method on the target class.

@Autowired
FileSystemStorageService service;

@PostConstruct
public void processFile() {
    service.readFile("test.txt");
}Code language: Java (java)

When we run this, we get:

INFO  | [main] c.a.s.a.s.FileSystemStorageService:13 - Reading file: test.txt
INFO  | [main] c.a.s.a.s.LoggingAspect:14 - After Executing targetCode language: plaintext (plaintext)

The After advice is correctly executed after the method is finished.

Get Method Signature in After Advice

We can also read the method signature in After advice. To do that, we need to add an argument of JoinPoint type to the advice. The JoinPoint instance provides us with information about the target class and the target method.

Next, is an example of reading method arguments in Spring AOP After advice.

@After("execution(* com.amitph.spring.aop.service.FileSystemStorageService.readFile(..)) ")
public void logAfterMethodCall(JoinPoint joinPoint) {
    String targetClass = joinPoint.getTarget().getClass().getSimpleName();
    String targetMethod = joinPoint.getSignature().getName();
    String arg = joinPoint.getArgs()[0].toString();

    log.info("After Executing {}.{} with argument: {}",
            targetClass, targetMethod, arg);
}Code language: Java (java)

Output:

INFO  | [main] c.a.s.a.s.FileSystemStorageService:13 - Reading file: test.txt
INFO  | [main] c.a.s.a.s.LoggingAspect:19 - After Executing FileSystemStorageService.readFile with argument: test.txtCode language: plaintext (plaintext)

Summary

This tutorial provided a quick introduction Spring AOP after advice. After advice runs after the target method is finished. It will also run, even if the method finishes in exception. Also, we practically learned how to apply @After advice in a Spring or Spring Boot project, and access method signature in the advice. For more on Spring & Spring Boot, please visit: Spring Tutorials.