AOP

Spring AOP @AfterReturning Advice Type Example

Welcome readers, in this tutorial, we will explore the @AfterReturning annotation of the spring aop module.

1. Introduction

  • Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
  • It creates applications that are packaged as jar and are directly started using an embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
  • It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
  • It helps in removing the boilerplate code, extra annotations, and xml configurations
  • It provides a powerful batch processing and manages the rest endpoints
  • It provides an efficient jpa-starter library to effectively connect the application with the relational databases

1.1 Aspect-Oriented Programming (AOP) in spring

It is object-oriented programming that enables developers to address the crosscutting concerns such as authentication, transaction, security or logging management in an application. It breaks the application logic into distinct parts (known as Concerns). There are five types of advice (Represents an action taken by an aspect at a joinpoint) in spring aop i.e.

  • Before Advice: It is represented by @Before annotation and executes a before joinpoint
  • After Returning Advice: It is represented by @AfterReturning annotation and executes after the joinpoint completes naturally. This annotation can intercept the returned result by using the returning attribute inside this annotation. Do note, the attribute name must correspond to the parameter name in the advice method
  • After Throwing Advice: It is represented by @AfterThrowing annotation and executes if a method exists by throwing an exception
  • After Advice: It is represented by @After annotation and executes after a joinpoint regardless of the joinpoint exist naturally or through an exceptional return
  • Around Advice: It is represented by @Around annotation and executes before and after a joinpoint

To understand the above concept, let us open the eclipse ide and implement the @AfterReturning annotation in the spring aop module using spring boot.

2. Spring AOP @AfterReturning Advice Type Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, and Maven.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring AOP @AfterReturning Advice Type - Application Structure
Fig. 1: Application Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring AOP @AfterReturning Advice Type - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Spring AOP @AfterReturning Advice Type - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring AOP @AfterReturning Advice Type - Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 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.spring.aop.afterreturning</groupId>
	<artifactId>Springaopafterreturningannotationtutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
</project>

We can start adding the dependency that developers want like spring boot, aop etc. Let us start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application.

3.1 Maven Dependency

Here, we specify the dependency for the spring boot and aop. Maven will automatically resolve the other dependencies. The updated file will have the following code.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	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.spring.aop.afterreturning</groupId>
	<artifactId>Springaopafterreturningannotationtutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>Spring Aop After Returning Advice tutorial</name>
	<description>An example to understand the after returning advice in spring aop</description>

	<!-- spring boot parent dependency jar. -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
	</parent>

	<dependencies>
		<!-- spring boot jar. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- to implement aop in a spring boot application. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-aop</artifactId>
		</dependency>
	</dependencies>
	<build>
		<finalName>Springaopafterreturningannotationtutorial</finalName>
	</build>
</project>

3.2 Java Classes

Following classes are required to understand the After Returning advice.

3.2.1 Bank Service class

Let us write a service class that has the deposit money. This class is annotated with the @Service annotation.

Mybank.java

package com.ducat.springboot.aop.service;

import org.springframework.stereotype.Service;

@Service
public class Mybank {

	public String depositMoney(String accNum) {
		String status = "";
		System.out.println(":::: Inside depositMoney() method :::");

		if(accNum.equals("12345")) {
			System.out.println("You have successfully deposited your amount.");
			status = "Success";
		} else {
			System.out.println("Account number mismatch.");
			status = "Failure";
		}

		return status;
	}
}

3.2.2 Employee Aspect class

Let us write the aspect class where we will define a pointcut expression and the @AfterReturning annotation to meet the cross-cutting concern of our application. This class is annotated with @Aspect and @Component annotations.

Myemployeeaspect.java

package com.ducat.springboot.aop.aspects;

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

// @Aspect annotation enables the spring aop functionality in an application. Tells the developer that this class has advice methods.
@Aspect
@Component
public class Myemployeeaspect {

	// Pointcut definition to display all the available methods i.e. the advice will be called for all the methods.
	@Pointcut(value= "execution(* com.ducat.springboot.aop.service.Mybank.*(..))")
	private void logAfterDeposit() { }

	// Method is executed after the method matching with a pointcut expression.
	// Here "returning" attribute is optional and it restricts matching to only those methods that return a value of the specified type (i.e. Object or it's subtype).
	@AfterReturning(value= "logAfterDeposit()", returning= "status")
	public void afterReturningAdvice(JoinPoint jp, Object status){
		System.out.println("Inside afterReturningAdvice() method...." + " Inserted after= " + jp.getSignature().getName() + " method");
		System.out.println("Money deposit status is= " + status);
	}  
}

3.2.3 Implementation/Main Class

Let us write the implementation/main class involved in this application. This class is the entry point of the spring boot application containing @SpringBootApplication, @EnableAspectJAutoProxy annotations, and the static main method.

Myapplication.java

package com.ducat.springboot.aop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import com.ducat.springboot.aop.service.Mybank;

@SpringBootApplication

// @EnableAspectJAutoProxy annotation enables support for handling the components marked with @Aspect annotation. It is similar to  tag in the xml configuration.
@EnableAspectJAutoProxy
public class Myapplication {

	public static void main(String[] args) {

		ConfigurableApplicationContext context = SpringApplication.run(Myapplication.class, args);

		// Fetching the employee object from the application context.
		Mybank bank = context.getBean(Mybank.class);

		// Depositing money in the account.
		String accnumber = "12345";
		bank.depositMoney(accnumber);

		// Closing the context object.
		context.close();
	}
}

4. Run the Application

To execute the application, right click on the Myapplication.java class, Run As -> Java Application.

Spring AOP @AfterReturning Advice Type - Run the Application
Fig. 5: Run the Application

5. Project Demo

The code shows the following logs as the output of this tutorial.

2019-02-15 10:04:58.782  INFO 13932 --- [           main] com.ducat.springboot.aop.Myapplication   : Started Myapplication in 1.05 seconds (JVM running for 1.481)

:::: Inside depositMoney() method :::
You have successfully deposited your amount.
Inside afterReturningAdvice() method.... Inserted after= depositMoney method
Money deposit status is= Success

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to create a simple spring aop application. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share! Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of After Returning advice in the spring aop module.

Download
You can download the full source code of this example here: Spring AOP @AfterReturning Advice Type Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button