DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Four Essential Tips for Building a Robust REST API in Java
  • Adding Versatility to Java Logging Aspect

Trending

  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  1. DZone
  2. Coding
  3. Java
  4. AOP for Post-Processing REST Requests With Spring and AspectJ

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.

By 
Alexander Rumyantsev user avatar
Alexander Rumyantsev
·
Feb. 07, 25 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
7.4K Views

Join the DZone community and get the full member experience.

Join For Free

Aspect-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.

Java
 
@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.

Java
 
@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:

Java
 
@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.

AspectJ REST Aspect (computer programming) Java (programming language)

Published at DZone with permission of Alexander Rumyantsev. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build a REST API With Just 2 Classes in Java and Quarkus
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Four Essential Tips for Building a Robust REST API in Java
  • Adding Versatility to Java Logging Aspect

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!