Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Spring Boot AOP Advice
3.
Spring Boot AOP After Throwing Advice
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Spring Boot AOP After Throwing Advice

Author Rajat Agrawal
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

AOP is the Aspect-Oriented Programming paradigm to increase modularity by separating cross-cutting concerns or secondary logic. The cross-cutting concerns are different from the main business logic. We can add additional behavior to the existing code without modifying the business logic.

Spring AOP framework will help us to implement these cross-cutting concerns.

Spring Boot AOP Advice is an action that we take either after or before the method execution. The action is a code that is invoked during the program execution.

Let’s now learn about the AOP Advice.

Spring Boot AOP Advice

AOP Advice is an action that we take either after or before the method execution. The action is a code that is invoked during the program execution.

There are five types of advice in the Spring AOP framework:

1.) Before Advice: The advice that executes before a join point is known as before advice. We use @Before annotation to mark advice as Before advice.

2.) After Advice: The advice that executes after a join point is known as after advice. We use @After annotation to mark advice as After advice.

3.) Around Advice: The advice that executes before and after a join point is known as around advice. We use @Around annotation to mark advice as Around advice.

4.) After Throwing Advice: The advice that executes when a join point throws an exception is known as after throwing advice. We use @After Throwing annotation to mark advice as After Throwing advice.

5.) After Returning Advice: The advice that executes when a method executes successfully is known as after returning advice. We use @After Returning annotation to mark advice as After Returning advice.

Spring Boot Starter AOP is the dependency that provides Spring AOP and AspectJ, where AOP provides basic AOP functionalities and the AspectJ provides the complete AOP framework.

Before implementing the AOP in a Spring Boot application, we need to add Spring AOP dependency in the pom.xml file.

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

 

Let’s understand the Spring Boot AOP After Throwing Advice in depth.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Spring Boot AOP After Throwing Advice

After Throwing Advice in Spring AOP invokes after a join point throws an exception. We use @After Throwing annotation to mark advice as After Throwing advice.

Let's implement the after-throwing advice in a Spring Boot application.

Step1: Create a basic Spring Boot application using Spring Tool Suite (STS) or Spring Intializr.

Step2: Before implementing the AOP After Throwing Advice in a Spring Boot application, we need to add Spring AOP dependency into the pom.xml file.

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

 

We have added the above dependency in the following picture:

Step3: Create a package with the name com.<name>.model. (For example: com.codingninjas.model) in src/main/java folder. This package will contain the different database models we design.

We have created a package with the name com.codingninjas.model in the following picture:

src/main/java->com.codingninjas.model

Step4: Create a class in the above package with the name Student.

In the above class, we have defined two variables, studentName, and studentDepartment of type String.

Student.java

package com.codingninjas.model;  
public class Student   
{  
private String studentName;  
private String studentDepartment;  
public Student(String studentName, String studentDepartment)   
{  
super();  
this.studentName = studentName;  
this.studentDepartment = studentDepartment;  
}
public String getStudentName()   
{  
return studentName;  
}  
public String getStudentDepartment()   
{  
return studentDepartment;  
}  
@Override  
public String toString()  
{  
return "Student [studentName=" + studentName+ ", studentDepartment=" + studentDepartment + "]";  
}  
}  

 

We have created the above class and method in the following picture:

Step5: Create another package with the name com.<name>.service.impl. (For example: com.codingninjas.service.impl). This package will contain the service component where business logic is written.

We have created a package with the name com.codingninjas.service.impl in the following picture:

src/main/java->com.codingninjas.service.impl 

Step6: Create a class in the above package with the name StudentServiceImpl.

In this class, we have defined student service.

StudentServiceImpl.java

package com.codingninjas.service.impl;
import java.util.HashMap;  
import java.util.Map;  
import java.util.Map.Entry;  
import java.util.Set;  
import org.springframework.stereotype.Service;  
import com.codingninjas.model.Student;  
@Service  
public class StudentServiceImpl implements StudentService   
{  
//storing student detail in the HashMap  
private static Map<String,Student> map = null;  
static  
{  
map = new HashMap<>();  
//adding student detail in the map  
map.put("STD01", new Student("Rajat", "Information Technology"));  
map.put("STD02", new Student("Rishab", "Electrical Engineering"));  
}  
@Override  
public Student getStudentByStudentId(String studentId) throws Exception  
{  
if(studentId ==null)  
{  
throw new Exception("Invalid! Student Id");  
}  
Student student= null;  
Set<Entry<String, Student>> entrySet = map.entrySet();  
for (Entry<String, Student> entry : entrySet)   
{  
if(entry.getKey().equals(studentId))  
{  
student= entry.getValue();  
}  
}  
return student;  
}  
}  

 

We have created the above class and method in the following picture:

Step7: Create an interface with the name StudentService in the package com.codingninjas.service.impl.

StudentService.java

package com.codingninjas.service.impl;
import com.codingninjas.model.Student;  
//creating interface that throws exception if the student id is not found   
public interface StudentService   
{  
public abstract Student getStudentByStudentId(String studentId)  
throws Exception;  
}  


We have created the above class in the following picture:

Step8: Create a package with the name com.<name>.aspect. (For example: com.codingninjas.aspect) in the src/main/java folder. This package will contain the AOP component, where we write our secondary logic.

We have created a package with the name com.codingninjas.aspect in the following picture:

src/main/java->com.codingninjas.aspect

Step 9: Create a class StudentAspect.java in the above package. In this class, we implemented the after throwing advice using the @AfterThrowing annotation. We have also defined a method named afterThrowingAdvice().

Note: The name (student here) that we define in the throwing attribute must be similar to the name of a parameter in the advice method.

StudentAspect.java

package com.codingninjas.aspect;
import org.aspectj.lang.JoinPoint;  
import org.aspectj.lang.annotation.AfterThrowing;  
import org.aspectj.lang.annotation.Aspect;  
import org.springframework.stereotype.Component;  
  
@Aspect  
@Component  
public class StudentAspect {
//implementing after throwing advice      
@AfterThrowing(value="execution(* com.codingninjas.service.impl.StudentServiceImpl.*(..))",throwing="exec")  
public void afterThrowingAdvice(JoinPoint joinPoint, Exception exec)  
{  
System.out.println("After Throwing Exception in method:"+joinPoint.getSignature());  
System.out.println("Exception is:"+exec.getMessage());  
}     
}

 

We have created the above class and method in the following picture:

Step10: Open <Application>.java (CodingNinjasApplication.java here) file and add an annotation @EnableAspectJAutoProxy.

The @EnableAspectJAutoProxy annotation enables support for handling components marked with @Aspect annotation. It is used along with the @Configuration annotation.

We have used the proxyTargetClass attribute of the annotation @EnableAspectJAutoProxy. The attribute proxyTargetClass=true allows us to use CGLIB (Code Generation Library) proxies instead of the default interface-based JDK proxy approach.

ConfigurableApplicationContext is an interface that provides convenience to configure an application context and the application context client methods in the ApplicationContext.

CodingNinjasApplication.java

package com.codingninjas;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
import org.springframework.context.ConfigurableApplicationContext;  
import org.springframework.context.annotation.EnableAspectJAutoProxy;  
import com.codingninjas.model.Student;  
import com.codingninjas.service.impl.StudentService;  
import com.codingninjas.service.impl.StudentServiceImpl;  

@SpringBootApplication  
@EnableAspectJAutoProxy(proxyTargetClass=true)  
public class CodingNinjasApplication 
{  
public static void main(String[] args)    
{  
ConfigurableApplicationContext ac = SpringApplication.run(CodingNinjasApplication.class, args);  
//Fetching the student object from the application context  
StudentService studentService = ac.getBean("studentServiceImpl", StudentServiceImpl.class);  
Student student;  
try   
{  
student = studentService.getStudentByStudentId(null);  
if(student != null)  
System.out.println(student.getStudentName()+"\t"+student.getStudentDepartment());  
}   
catch (Exception e)   
{  
System.out.println(e.getMessage());  
}  
}  
}  

 

We have implemented the above code in the following picture:

Step11: Run the CodingNinjasApplication.java file as a java application.

Output: 

The above output shows that the method afterThrowingAdvice() invokes when the  getStudentByStudentId() method throws an exception.

Must Read Spring Tool Suite

FAQs

  1. Why is AOP used in Spring Boot?
    AOP stands for Aspect-Oriented Programming. It is used to increase modularity by separating cross-cutting concerns or secondary logic.
     
  2. Types of Advice in Spring AOP framework?
    There are five types of advice in the Spring AOP framework: before, after, after-returning, after-throwing, and around advice.
     
  3. What is the use of @EnableAspectJAutoProxy annotation?
    The @EnableAspectJAutoProxy annotation enables support for handling components marked with @Aspect annotation. It is used along with the @Configuration annotation.

Key Takeaways

In this blog, we learned about Spring Boot AOP Advice, different types of AOP advice, and implementation of AOP After Throwing Advice.

You can also check how to carry out the STS Download.

Happy Learning!!

Live masterclass