SpringTechnology

Spring AOP @AfterReturning Advice with Examples

Hands on Guide to Spring AOP @AfterReturning advice with examples in Spring as well as Spring Boot.

What is Spring AOP AfterThrowing Advice?

The Aspect Oriented Programming helps segregation of cross cutting concerns in application. Using AOP we store the cross cutting concerns in the form of advices. The AfterReturning advice is a type of advice that runs after a successful completion of the target method.

Thus, we can use the AfterReturning advice to post process the objects the target method returns. However, it is important to note that the AfterReturning advice does not run if the target method throws any exception.

Spring AOP Setup

Next are the initial steps, that we have to follow to Setup Spring AOP and to create and run an advice.

Dependency

At first, we need to add spring-aspects dependency to our project. Next, is an example of adding the dependency to a maven pom.xml file.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>{spring.aop.version}</version>
</dependency>

Enable AspectJ Proxies

In order for Spring AOP to apply advices on the given targets, we need to enable the Proxy support. To do that, we have to use @EnableAspectJAutoProxy annotation on a configuration class.

@Configuration
@EnableAspectJAutoProxy
public class ApplicationConfig {
    ...

This step is required for a Spring Application. However, for Spring Boot application we can skip it as Spring Boot automatically enables proxies when it finds the dependency.

Create Target Class

Next, we will create a target class and a target method. Our target method returns a List of String values.

@Slf4j
@Service
public class FileSystemStorageService {

    public List<String> readFile(String name) {
        log.info("Reading file: {}", name);
        //
        return List.of("Text from file");
    }
}

Target Method Invoker

Now, we will write a class that invokes the target method from a @PostConstruct method. Thus, the target method runs as soon as the application starts up.

@Autowired
FileSystemStorageService service;

@PostConstruct
public void processFile() {
    service.readFile("test.txt");
}

Note that, we have not yet added any advice on the target method. Thus, the when the invoker runs it will invoke the target method as any normal Java method.

Spring AOP AfterReturning Advice

Next, we will write our AfterReturning advice. Like any other Spring AOP advices, the AfterReturning advice is a normal Java method, except that we have to add @AfterReturning annotation and a Pointcut expression.

The Pointcut expression, maps to the signature, class, and package of the target method and the advice is applied to all such matching methods.

Example of @AfterReturning Advice in Spring AOP

@Slf4j
@Aspect
@Component
public class LoggingAspect {
    @AfterReturning("execution(* com.amitph.spring.aop.service.FileSystemStorageService.readFile(..))")
    public void logBeforeMethodCall(JoinPoint joinPoint, Exception ex) {

        log.error("Target method successfully completed");
    }
}

Note that the above advice will be applied to any readFile method from the given class. Next, we will start the application and watch the logs.

INFO  | [main] c.a.s.a.s.FileSystemStorageService:16 - Reading file: test.txt
ERROR | [main] c.a.s.a.s.LoggingAspect:16 - Target method successfully completed

From the logs it is clear that the advice ran right after the target method.

Read Object Returned By Target Method

Next, we will see how to read object returned by method in AfterReturning advice. To do that we need to add the returned object as the advice method argument. Also, we need to map the argument name into the returning attribute of @AfterReturning.

Example of accessing value returned by the target method in AfterReturning Advice.

@Slf4j
@Aspect
@Component
public class LoggingAspect {
    @AfterReturning(
            value = "execution(* com.amitph.spring.aop.service.FileSystemStorageService.readFile(..))",
            returning = "returned")
    public void logAfterReturning(List<String> returned) {

        log.error("Target method successfully completed, result: {}", returned);
    }
}

Output:

INFO  | [main] c.a.s.a.s.FileSystemStorageService:16 - Reading file: test.txt
ERROR | [main] c.a.s.a.s.LoggingAspect:18 - Target method successfully completed, result: [Text from file]

The logs show that the advice accessed the returned object correctly.

Summary

We had an Introduction to Spring AOP @AfterReturning type of advice. The AfterReturning advice runs after a successful completion of a target method. Also we covered examples of writing an AfterReturning advice in a Spring or Spring Boot application.

For more on Spring and Spring Boot, please visit Spring Tutorials.