Spring AOP — @AfterReturning

theoneamin
2 min readJun 24, 2022

As part of spring AOP, the @AfterReturning annotation can be used to do something whenever another thing is returned by a method.

For example, we could have it so that whenever a new user is registered, we queue a message to a message broker so that it can be consumed by another microservice that sends welcome emails to the users.

Enable aspect

First, let’s enable aspect proxy by adding the following annotation to our main class. This allows handling of any component marked @Aspect within your application.

Create class to handle after return

Then we’ll create a class to handle queuing users to a message broker. We’ve added a UserRegisterAspect class where we first autowire RabbitTemplate so we can queue messages to rabbitMQ but you can use Kafka producer if needed.

Then we add an after-return advice method which is annotated with @AfterReturning. In the annotation, we set the value as the path of the method we are targeting, and returning is set to whatever the createUser method returns, in our case a userDTO.

Don’t forget to annotate this class as @Aspect. Then run your application and whenever the createUser method is called, a message should be queued to rabbitMQ.

As always, hope you found this helpful. If you have any suggestions that would be useful to other readers, please leave them in the comments. Thanks for reading.

--

--