Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot - AOP After Throwing Advice
Next article icon

Spring Boot - AOP After Throwing Advice

Last Updated : 03 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
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


 


Next Article
Spring Boot - AOP After Throwing Advice

J

jackhammervyom
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Spring Boot - AOP Around Advice
    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 transa
    6 min read
    Spring Boot - Auto-configuration
    Spring Boot is heavily attracting developers toward it because of three main features as follows: Auto-configuration - such as checking for the dependencies, the presence of certain classes in the classpath, the existence of a bean, or the activation of some property.An opinionated approach to confi
    5 min read
    Spring Boot - EhCaching
    EhCache is an open-source and Java-based cache. It is used to boost performance. Its current version is 3. EhCache provides the implementation of the JSR-107 cache manager. Features of EhCache are given below: It is fast, lightweight, Flexible, and Scalable.It allows us to perform Serializable and O
    5 min read
    Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    3 min read
    Spring Boot - Starter Test
    Spring Boot is built on top of the spring and contains all the features of spring. It is becoming a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration and setup.
    5 min read
    Exception Handling in Spring Boot
    Exception handling in Spring Boot helps deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Key Approaches
    8 min read
    Spring Boot - Project Deployment Using Tomcat
    Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready envir
    5 min read
    Spring Boot - Difference Between AOP and OOP
    AOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business
    3 min read
    Spring Boot - Difference Between AOP and AspectJ
    Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and se
    3 min read
    Spring Boot - Logging
    Logging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spr
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences