Open In App

Spring Boot – AOP After Throwing Advice

Last Updated : 03 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring is widely used for creating scalable applications. For web applications Spring provides. Spring MVC is a widely used module of spring that is used to create scalable web applications. While Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transaction, logging not central to business logic without cluttering the code core to its functionality.

Note: It is a must to have an understanding of  Spring boot and aspect-oriented programming 

What is After Throwing Advice?

We know that spring uses standard J2SE dynamic proxies or CGLIB proxies to proxy a target object. Aspect-oriented programming is concerned with addressing cross-cutting concerns like logging and securing multiple layers like controller, service layer, DAO, etc.

After throwing advice is executed if a proxied object while executing the target method throws an exception. Note that the object is only proxied if the join point matches the pointcut expression. Note that proxies in Spring AOP are created at runtime and join point always represents a method execution in Spring AOP.

Let’s see after throwing advice with the help of an example.

Generating the basic project with the help of Spring initializr

Head onto Spring Initializr and copy the configuration mentioned below.

After selecting this configuration, click on generate project, extract the ZIP file and open it in any IDE of your choice.

There is one more dependency to be added, spring removed the AOP starter from the add dependency list so we would have to add it manually, just add the under-mentioned dependency to your pom.xml file.

XML




<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>


 
 

Step 1: Let’s first create a package under com.geeksforgeeks.demo called dao in which we will create our mock data access object. Usually, projects contain an intermediate layer between controller and dao called the service layer but to keep things simple we will directly transfer data from dao to the controller.

 

Example:

 

Java




// Java Program to illustrate MockDAO Class
 
// Importing required classes
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Repository;
 
// Annotation
@Repository
 
// Class
public class MockDAO {
 
    // Not actually accessing a database,
    // just giving a mock data
    public List<String> getEmployees(boolean exception)
    {
        if (exception) {
            throw new RuntimeException("You asked for it");
        }
 
        return Arrays.asList("Mary", "Jerome", "Vyom");
    }
}


 
 

@Repository is used to specify that the class provides a mechanism for storage, update, delete, etc. But to keep things simple we will just add the read operation. We have a parameter called exception which will be used as a flag, whether to throw an exception or not.

 

Step 2: Now that we have set up our dao, let’s set up the controller, create a package named controller under com.geeksforgeeks.demo

 

Example:

 

Java




// Java Program to Illustrate DefaultWebController Class
 
// Importing required classes
import com.geeksforgeeks.springbootaopafterthrowing.dao.MockDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
 
// Annotation
@Controller
 
// Class
public class DefaultWebController {
 
    // Class data member
    private final MockDAO mockDAO;
 
    // Annotation
    @Autowired public DefaultWebController(MockDAO mockDAO)
    {
        // This keyword refers to current instance itself
        this.mockDAO = mockDAO;
    }
 
    // Annotation
    @GetMapping("/")
 
    // Method
    public String homePage(Model model)
    {
        model.addAttribute("list",
                           mockDAO.getEmployees(false));
        return "index";
    }
}


 
 

Nothing special under the controller, we just specify a get mapping for the default landing page, add an attribute to the model, and pass to the index.html page. 

 

Step 3: After that, we will add the index.html page under resources.templates package.

 

HTML




<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Homepage</title>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>Name:</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="emp : ${list}">
        <td th:text="${emp}"></td>
    </tr>
    </tbody>
</table>
</body>
</html>


 
 

Not a fancy HTML page, just a very simple one. Don’t worry if you don’t know about Thymeleaf, we basically access that model attribute that was passed by the DefaultWebController, as a list was passed on, we just iterate over each entry and print it out.

 

We have the basic setup to run this on our system and check whether the web app is working right now (without the aspect part).

 

Step 4: Just open the project in the terminal and run 

 

mvn spring-boot:run

 

The project will startup, open your browser, and open http://localhost:8080/ you should see a similar page-

 

Output

 

Step 5: After we have reached this step, now it’s time to add an aspect to our code. So, creating a package called aspect under ‘com.geeksforgeeks.demo’

 

Example

 

Java




// Java Program to Illustrate LoggingAspect Class
 
// Importing required classes
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
 
// Annotation
@Aspect
@Component
 
// Class
public class LoggingAspect {
 
    // Annotation
    @AfterThrowing(
        "execution(public java.util.List com.geeksforgeeks.demo"
        + ".dao.MockDAO.getEmployees(..))")
 
    public void
    afterThrowingExceptionAdvice()
    {
        // Print statement
        System.out.println(
            "\n ======>> Oh No an exception was thrown\n");
    }
}


 
 

Spring AOP generates proxies at runtime so we need to annotate the class with @Component, these will be used as beans and injected by spring under the hood. @Aspect specifies that this is an aspect, it comes from the AspectJ library.

 

The @AfterThrowing annotation does exactly what its name means, it is executed after the method specified in the pointcut expression throws an exception. The program just prints to the console after an exception is thrown.

 

The pointcut expression specifies the method after which the advice should be executed-

 

public java.util.List com.geeksforgeeks.demo.dao.MockDAO.getEmployees(..)

 

This is the name of the method with the complete path of return type and the method name itself, (..)  matches a method with 0 or more arguments of any type.

 

Step 6: Now let’s see this in action, just change the false to true in the controller code-

 

model.addAttribute("list", mockDAO.getEmployees(true));

 

Again let’s run the program with mvn spring-boot:run, after the program starts up just visit http://localhost:8080/

 

Yay, Success the page failed to load as we threw an exception before returning the view name could be forwarded to the view resolver. You should see the following output as displayed below as follows: 

 

Output

 

And our terminal output should be similar to as shown below as follows:

 

Terminal Output

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads