AOP for Post-Processing REST Requests With Spring and AspectJ
This article discusses an example of using AOP in a Spring application for entity removal after a successful REST response was sent to the client.
Join the DZone community and get the full member experience.
Join For FreeAspect-oriented programming (AOP) is a programming paradigm that enables the modularisation of concerns that cut across multiple types and objects. It provides additional behavior to existing code without modifying the code itself.
AOP can solve many problems in a graceful way that is easy to maintain. One such common problem is adding 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. Before that, you can find more about AOP in Spring here.
Possible Solutions
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
). Spring components 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.
Implementation
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);
}
}
@Component
– marks the class as a Spring component so that it can be managed by the Spring IoC.@Aspect
– indicates that this class is an aspect. It is automatically detected by Spring and used to configure Spring AOP.@Pointcut
– indicates a predicate that matches join points (points during the execution of a program).execution()
– represents the execution of any method within the defined package (in our case the exact method name was set).@AfterReturning
– advice to be run after a join point completes normally (without throwing an exception).
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)));
}
}
Conclusion
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 on creating a service for sensitive data using Spring and Redis.
The source code of the full version of this service is available on GitHub.
Published at DZone with permission of Alexander Rumyantsev. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments