Spring Boot AOP Before Implementation

Spring Boot AOP Before Implementation

In this article, I am going to discuss Spring Boot AOP Before Implementation. Please read our previous article where we discussed Introduction to Spring Boot AOP.

Spring Boot AOP Before Implementation

In the previous article, we learned the theory of aspect-oriented programming (AOP). In this article, we will learn to implement it in Spring Boot. First, we shall start with the Before AOP implementation. We will use the fruits project again as we require a REST API.

Step 1: Make a copy of the fruits project and open the project in VS Code. The file structure must be as follows:

Spring Boot AOP Before Implementation

Step 2: Delete the following files from the project. This is because they may interfere with the operation of the project:

  • FruitExceptionController.java
  • FruitNotFoundException.java
  • FruitServiceInterceptor.java
  • FruitServiceInterceptorAppConfig.java

After deletion, the project structure should look like this:

Spring Boot AOP Before Implementation

Step 3: Add AOP dependency to the project. This is done by adding the following line to the pom.xml file:

Spring Boot AOP Before Implementation

Step 4: Create a new file called FruitServiceAspect.java in src/main/java/com/dotnet/restful directory.

Step 5: Import the following classes:

Spring Boot AOP Before Implementation

Step 6: Add the following code:

Spring Boot AOP Before Implementation

We have added the following lines:

  1. @Aspect and @Component annotations to the class. This signifies that the class is an Aspect class.
  2. Added a before function using the @Before annotation. This function should execute before sending the advice.

Step 7: Compile and execute the application. Ensure compilation is successful:

Spring Boot AOP Before Implementation

Step 8: Go to the webpage http://localhost:8080/view-products from your browser. The following output must be visible:

Spring Boot AOP Before Implementation

In the VS Code terminal, the following output must be visible:

Spring Boot AOP Before Implementation

We can see from the output that the before advice function executes. Congratulations! You now know how to implement AOP in Spring Boot! In the next article, we will cover other implementations of AOP, such as After Advice, Around Advice, etc.

The Complete Example Code:
Fruits.java – The POJO class
package com.dotnet.restful;

public class Fruits {
    private String id;
    private String name;
 
    public String getId()               {return id;}
    public void setId(String id)        {this.id = id;}
    public String getName()             {return name;}
    public void setName(String name)    {this.name = name;}

    public Fruits (String nid, String nname)
    {
        id = nid;
        name = nname;
    }
 }
FruitService.java – The class responsible for handling the CRUD operations.
package com.dotnet.restful;

import java.util.Collection;

public interface FruitService
{
    public abstract void createFruit (Fruits fruits);
    public abstract void updateFruit (String id, Fruits fruits);
    public abstract void deleteFruit (String id);
    public abstract Collection<Fruits> getFruits();
}
FruitServiceAspect.java – The file containing the AOP code.
package com.dotnet.restful;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class FruitServiceAspect
{
    //Before AOP for getFruits();
    @Before(value = "execution(* com.dotnet.restful.FruitService.*(..)) and args()")
    public void beforeAdvice(JoinPoint joinPoint)
    {
        System.out.println("Before method: " + joinPoint.getSignature());
        System.out.println("getFruits();");
    }
}
FruitServiceController.java – The class responsible for providing the REST API.
package com.dotnet.restful;

import org.springframework.beans.factory.annotation.Autowired;
//Required web classes
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FruitServiceController
{
   @Autowired
   FruitService fruitService;

   @RequestMapping(value = "/products")
   public ResponseEntity<Object> getProduct() {
      return new ResponseEntity<>(fruitService.getFruits(), HttpStatus.OK);
   }

   @RequestMapping(value = "/products/{id}", method = RequestMethod.PUT)
   public ResponseEntity<Object> updateProduct(@PathVariable("id") String id, @RequestBody Fruits fruits)
   { 
      fruitService.updateFruit(id, fruits);
      return new ResponseEntity<>("Fruit is updated!", HttpStatus.OK);
   }
   
   @RequestMapping(value = "/products/{id}", method = RequestMethod.DELETE)
   public ResponseEntity<Object> delete(@PathVariable("id") String id)
   {
      fruitService.deleteFruit(id);
      return new ResponseEntity<>("Fruit is deleted!", HttpStatus.OK);
   }
   
   @RequestMapping(value = "/products", method = RequestMethod.POST)
   public ResponseEntity<Object> createProduct(@RequestBody Fruits product)
   {
      fruitService.createFruit(product);
      return new ResponseEntity<>("Fruit is created!", HttpStatus.CREATED);
   }
}
FruitServiceImpl.java – The class in which the CRUD operations occur.
package com.dotnet.restful;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

@Service
public class FruitServiceImpl implements FruitService
{
    private static Map<String,Fruits> database = new HashMap<>();
    static {
        Fruits apple = new Fruits("1","Apple");
        database.put(apple.getId(), apple);
  
        Fruits banana = new Fruits("2","Banana");
        database.put(banana.getId(), banana);
  
        Fruits chiku = new Fruits("3","Chiku");
        database.put(chiku.getId(), chiku);
  
        Fruits dragon = new Fruits("4","Dragon Fruit");
        database.put(dragon.getId(), dragon);
     }

    @Override
    public void createFruit(Fruits fruits)  {database.put(fruits.getId(), fruits);}
    @Override
    public void deleteFruit(String id)      {database.remove(id);}
    @Override
    public Collection<Fruits> getFruits()   {return database.values();}

    @Override
    public void updateFruit(String id, Fruits fruits)
    {
        database.remove(id);
        fruits.setId(id);
        database.put(id, fruits);
    }
}
RestfulApplication.java – The class containing the main() function.
package com.dotnet.restful;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestfulApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestfulApplication.class, args);
    }

    @Bean
    public RestTemplate getRestTemplate ()
    {
        return new RestTemplate();
    }
}
WebController.java – The class responsible for providing web services.
package com.dotnet.restful;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController
{
    @RequestMapping(value = "/view-products")
    public String viewProducts()    {return "view-products";}

    @RequestMapping(value = "/add-products")
    public String addProducts()    {return "add-products";}
}
add-products.html
<!DOCTYPE html>
<html>
   <head>
      <title>Add Products</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      
      <script>
         $(document).ready(function() {
            $("button").click(function() {
               var productmodel = {
                  id : "5",
                  name : "Fig"
               };
               var requestJSON = JSON.stringify(productmodel);
               $.ajax({
                  type : "POST",
                  url : "http://localhost:8080/products",
                  headers : {
                     "Content-Type" : "application/json"
                  },
                  data : requestJSON,
                  success : function(data) {
                     alert(data);
                  },
                  error : function(data) {
                  }
               });
            });
         });
      </script>
   </head>
   
   <body>
      <button>Click here to submit the form</button>
   </body>
</html>
view-products.html
<!DOCTYPE html>
<html>
   <head>
      <title>View Products</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

      <script>
         $(document).ready(function(){
            $.getJSON("http://localhost:8080/products", function(result){
               $.each(result, function(key,value) {
                  $("#productsJson").append(value.id+" "+value.name+" ");
               }); 
            });
         });
      </script>
   </head>
   
   <body>
        <h1>Fruits: </h1>
        <div id = "productsJson"> </div>
   </body>
</html>

In the next article, I am going to discuss Spring Boot AOP Other Implementations with Examples. Here, in this article, I try to explain Spring Boot AOP Before Implementation with Examples. I hope you enjoy this Spring Boot AOP Before Implementation article.

Leave a Reply

Your email address will not be published. Required fields are marked *