Aspect-oriented Programming (AOP) is a programming paradigm that enables the modularization of concerns that cut across multiple types and objects. It provides additional behavior to existing code without modifying the code itself. More about AOP in Spring is
AOP can solve many problems in a graceful way that is easy to maintain. One such common problem is to add some new behavior to a controller (@Controller) so that it works “outside” the main logic of the controller. In this article, we will look at how to use AOP to add logic when an application returns a successful response (HTTP 200). An entity should be deleted after it is returned to a client.
This can relate to applications that for some reason (e.g. legal) cannot store data for a long time and should delete it once it is processed. We will be using AspectJ in the Spring application. AspectJ is an implementation of AOP for Java and has good integration with Spring.
To achieve our goal and delete an entity after the logic in the controller was executed we can use several approaches. We can implement an interceptor (HandlerInterceptor) or a filter (OncePerRequestFilter). These are Spring components that can be leveraged to work with HTTP requests and responses. This requires some studying and understanding this part of Spring.
Another way to solve the problem is to use AOP and its implementation in Java - AspectJ. AOP provides a possibility to reach the solution in a laconic way that is very easy to implement and maintain. It allows you to avoid digging into Spring implementation to solve this trivial task. AOP is a middleware solution and complements Spring.
Let’s say we have a CardInfo entity that contains sensitive information that we cannot store for a long time in the database and we are obliged to delete the entity after we process it. For simplicity, by processing, we will understand just returning the data to a client that makes a REST request to our application.
We want the entity to be deleted right after it was successfully read with a GET request. We need to create a Spring Component and annotate it with @Aspect.
@Aspect
@Component
@RequiredArgsConstructor
@ConditionalOnExpression("${aspect.cardRemove.enabled:false}")
public class CardRemoveAspect {
private final CardInfoRepository repository;
@Pointcut("execution(* com.cards.manager.controllers.CardController.getCard(..)) && args(id)")
public void cardController(String id) {
}
@AfterReturning(value = "cardController(id)", argNames = "id")
public void deleteCard(String id) {
repository.deleteById(id);
}
}
I also annotated the class with @ConditionalOnExpression to be able to switch on/off this functionality from properties.
This small piece of code with a couple of one-liner methods does the job that we are interested in. The cardController(String id)
method defines the exact place/moment where the logic defined in the deleteCard(String id)
method is executed. In our case, it is the getCard()
method in the CardController class that is placed in com.cards.manager.controllers package.
deleteCard(String id)
contains the logic of the advice. In this case, we call CardInfoRepository
to delete the entity by id. Since CardRemoveAspect
is a Spring Component, one can easily inject other components into it.
@Repository
public interface CardInfoRepository extends CrudRepository<CardInfoEntity, String> {
}
@AfterReturning shows that the logic should be executed after a successful exit from the method defined in cardController(String id)
.
CardController looks as follows:
@RestController
@RequiredArgsConstructor
@RequestMapping( "/api/cards")
public class CardController {
private final CardService cardService;
private final CardInfoConverter cardInfoConverter;
@GetMapping("/{id}")
public ResponseEntity<CardInfoResponseDto> getCard(@PathVariable("id") String id) {
return ResponseEntity.ok(cardInfoConverter.toDto(cardService.getCard(id)));
}
}
AOP represents a very powerful approach to solving many problems that would be hard to achieve without it or difficult to maintain. It provides a convenient way to work with and around the web layer without the necessity to dig into Spring configuration details.
To view the full example application where AOP was used as shown in this article, read my other article about Creating a Service for Sensitive Data with Spring and Redis.
The source code of the full version of this service is available on GitHub.