The Wayback Machine - https://web.archive.org/web/20240907061256/https://www.geeksforgeeks.org/spring-boot-aop-after-advice/
Open In App

Spring Boot – AOP After Advice

Last Updated : 02 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Aspect Oriented Programming and AOP in Spring Framework

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. It does so by adding additional behavior that is the advice to the existing code. For example- Security is a crosscutting concern, in many methods in an application security rules can be applied, therefore repeating the code at every method, defining the functionality in a common class and control were to apply that functionality in the whole application. In this article, we will be covering a working example of After Advice.

After Advice is executed after a join point execution.  It is denoted by @After annotation. The advice method is executed irrespective of the execution flow of the matched method. Whether the method is executed normally or any exception occurs after advice will be executed anyways. This is contrary to the execution of after-returning, where advice is run only if the method completes successfully, and after-throwing where advice is run only if the method exits by throwing an exception. After advice is generally used for releasing resources.

Steps to Implement AOP After Advice in Spring Boot Application

Step 1: Open Spring Initializer http://start.spring.io

Step 2: Provide the Group name: com.after_advice

Step 3: Provide the Artifact Id: aop-after-advice-example

Step 4: Add the Spring Web dependency.

Step 5: Click on the Generate button. A zip file will be downloaded into the system. Extract it.

Step 6: Import the folder in the IDE by using the following steps:

File -> Import -> Existing Maven Projects -> Next -> Browse -> Look for the folder aop-after-advice-example -> Finish. When the project is imported, it will install the dependencies. Once it is done, follow the next steps.

Step 7: Add the dependency for spring AOP in pom.xml

pom.xml file:

XML




         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.before_advice</groupId>
 <artifactId>aop-before-advice-example</artifactId>
 <version>0.0.1-SNAPSHOT</version>
  
 <packaging>jar</packaging> 
 
 <name>aop-before-advice-example</name>
 <description>Demo project for Spring Boot</description>
 
  <parent>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.2.2.RELEASE</version>
     <relativePath /> <!-- lookup parent from repository -->
  </parent>
 
  <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
     <java.version>1.8</java.version>
  </properties>
 
    <dependencies>
       <!-- dependency for spring web -->
       <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
  
       <!-- added dependency for spring aop -->
       <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    </dependencies>
 
<build>
 <plugins>
  <plugin>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-maven-plugin</artifactId>
  </plugin>
 </plugins>
</build>
 
</project>


 
 

Save the changes and it will download the jars. Once it is done, move ahead with the next steps.

 

Note: If the jars are not added properly, you may get some errors.

 

Step 8: Create a package with the name com.after_advice.model. and add a Student model class to it.

 

Student class:

 

Java




package com.after_advice.model;
 
public class Student {
    private String firstName;
    private String secondName;
 
    public Student() {
    }
 
    public String getFirstName() {
        return firstName;
    }
 
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
 
    public String getSecondName() {
        return secondName;
    }
 
    public void setSecondName(String secondName) {
        this.secondName = secondName;
    }
}


Step 9: Create a package with the name com.after_advice.service. and add a Student Service class to it. Add a method to add students with given name arguments.

StudentService class:

Java




package com.after_advice.service;
 
import org.springframework.stereotype.Service;
 
import com.after_advice.model.Student;
 
@Service
public class StudentService {
 
    public Student addStudent(String fname, String sname) {
        System.out.println("Add student service method called");
        Student stud = new Student();
        stud.setFirstName(fname);
        stud.setSecondName(sname);
        if(fname.length()<=3)
            throw new RuntimeException("Length of firstname must be 4 or more" );
        return stud;
    }
 
}


 
 

Step 10: Create a package with the name com.after_advice.controller. and add a Student Controller class to it. Add a method to handle Get requests and call Student Service from it.

 

StudentController class:

 

Java




package com.after_advice.controller;
 
import com.after_advice.model.Student;
import com.after_advice.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class StudentController {
 
    @Autowired private StudentService studentService;
 
    @GetMapping(value = "/add")
    public Student addStudent(
        @RequestParam("firstName") String firstName,
        @RequestParam("secondName") String secondName)
    {
        return studentService.addStudent(firstName,
                                         secondName);
    }
}


 
 

Step 11: Create a package with the name com.after_advice.aspect. and add a Student Service Aspect class to it. Here we will add our Advice method and PointCut expression.

 

StudentServiceAspect class:

 

Java




package com.after_advice.aspect;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
 
@Aspect
@Component
public class StudentServiceAspect {
   
    // the pointcut expression specifying execution of any
    // method in com.after_advice.service.StudentService
    // class of any return type with 0 or more number of
    // arguments
    @Pointcut("execution(* com.aftere_advice.service.StudentService.*(..)) ")
      // the pointcut signature
    private void anyStudentService()  { }
 
    @After("anyStudentService() && args(fname, sname)")
    public void afterAdvice(JoinPoint joinPoint,
                             String fname, String sname)
    {
        System.out.println(
            "After method:" + joinPoint.getSignature()
            + "\n "
            + "Added Student with first name - " + fname
            + ", second name - " + sname);
    }
}


 
 

Step 12: We are done with the code structure. Now to run the application, start the application as “run as boot application”. Open the browser and hit the following URL to make a get request call: http://localhost:{portNumber}/add?firstName={fname}&secondName={sname}

 

 

For a demo, we are hitting URL with fname as Harry and sname as Potter. In this case, the method will be executed normally.

 

 

When we hit URL with fname as Tom, the service method will throw an exception. The After advice will be executed.

 

 

As seen in the output, the advice method is called after the service method is executed successfully or any exception is raised. 

 



Previous Article
Next Article

Similar Reads

Spring Boot - AOP After Throwing Advice
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
6 min read
Spring Boot - AOP After Returning Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework 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 con
5 min read
Spring Boot - AOP Before 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 transaction, logging not central to business logic witho
4 min read
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 transaction, logging not central to business logic witho
6 min read
Spring - AOP Example (Spring1.2 Old Style AOP)
Spring AOP allows adding additional behavior to the existing code without its modification. The Spring 1.2 Old Style AOP is supported in Spring 3 but there are a few things such as advice domain objects, that can not be done easily with Spring AOP. The AspectJ is the best available option in that case. And so, it is recommended to use Spring AOP wi
9 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 logic. It is more convenient to use because change
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 setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot - AOP(Aspect Oriented Programming)
The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the end-user using REST API or the web application.Busi
4 min read
How to Implement AOP in Spring Boot Application?
AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of APIs for cross-cutting requirements. Logging modu
10 min read
Spring AOP vs Spring IOC
Spring AOPAspect Oriented Programming i.e. AOP, is another way to program a structure, similar to Object-oriented Programming (OOP). Object-oriented Programming (OOP) completely depends upon classes as the main modular unit, whereas Aspect Oriented Programming (AOP) moves the main idea to aspects. Aspects are the essential element that allows probl
4 min read
Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project
Spring AOP has come up with different annotations namely @Before, @After, @Around,@AfterReturning, and @AfterThrowing. Usually, confusions occur among developers were to write the apt code among these annotations. In this article, let us see them by using a sample application. @Around This is the most effective advice among all other advice. The fi
9 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 setup. Spring Boot is a microservice-based framework
3 min read
Spring Boot – Handling Background Tasks with Spring Boot
Efficiently handling background tasks with Spring Boot is important for providing a smooth user experience and optimizing resource utilization. Background tasks refer to operations that are performed asynchronously or in the background, allowing the main application to continue processing other requests. In a Spring Boot application, background tas
5 min read
Spring Boot – Using Spring Boot with Apache Camel
Apache Camel and Spring Boot are two powerful frameworks that can be seamlessly integrated to build robust, scalable, and efficient applications. Apache Camel is an open-source integration framework that provides an extensive range of components and connectors, enabling developers to integrate different systems, APIs, and applications. It simplifie
5 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Spring - AOP AspectJ Xml Configuration
Spring allows you to specify aspects, recommendations, and pointcuts in an XML file. Annotations were used in the aop examples on the preceding page. The XML configuration file will now show us the same samples. Let's look at the XML components that describe advice. aop:before: It's used before the real business logic procedure is called.aop:after:
7 min read
Spring AOP - AspectJ Annotation
AOP i.e Aspect-Oriented Programming complements OOP by enabling modularity of cross-cutting concerns. @AspectJ is mainly used for declaring aspects as regular Java classes annotated with annotations. Spring AspectJ AOP implementation has many annotations. They are explained below: @Aspect: It declares the class as an aspect.@Pointcut: It declares t
4 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
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 setup. Spring Boot is a microservice-based framework
3 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
What's New in Spring 6 and Spring Boot 3?
Spring and Spring Boot are two of the most popular Java frameworks used by developers worldwide. The Spring team is continuously working on improving and enhancing the frameworks with each new major release. Spring 6 and Spring Boot 3 are expected to bring in significant new features and changes that will further boost development with these techno
5 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizatio
2 min read
Java Spring Boot Microservices - Integration of Eureka, Feign & Spring Cloud Load Balancer
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
Difference between Spring and Spring Boot
Spring Spring is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier compared to classic Java frameworks and Appl
4 min read