Spring AOP – @Around Advice

Facebooktwitterredditpinterestlinkedinmailby feather

Spring AOP – @Around Advice

We have discussed in our previous tutorial, the concepts, and terminology of the Spring AOP. Around advice is one of the types of advices. It can be applied to a method before and after the method execution. It acts as the most powerful kind of advice.

Let’s understand the Around advice briefly with the help of an example.

Example of @Around Advice

Here, we are going to create an example of around advice using the @Around annotation.

Following are the steps to create an example of @Around advice:

  • Create a DAO class

In this step, we are going to create a DAO class name Service that contains business logic. In this class, we have defined a method named delay() that will produce a delay of 10 seconds in the output.

Service.java

  • Create a class that performs component scanning

In this step, we are going to create a class named DemoAOP that performs component scanning.

DemoAOP.java

  • Create an aspect class for aspect logic

In this step, we are going to create a class named AspectClass, that contains the aspect logic (advice types).

AspectClass.java

  • Create the main class

In this step, we are going to create the main class named App that contains the main method.

App.java

OUTPUT

The following output shows that the @Around advice is applied to the method delay(). It also shows the total duration of execution.

Spring AOP – @Around Advice

Around Advice using Logger

Logger – Logger is an interface used to log messages for a specific application. Through the Logger interface, we can also log operations. It is available in the org.apache.log4j package.

Following code snippet shows how to use Logger:

In the above code snippet, the newlogger is an object of the Logger class.

Let’s understand the concept of Logger with the help of an example.

Example of around advice using Logger

Here, we are going to create an example of Around advice using Logger. We are using the previous example with some modifications.

In the following example, we are going to replace System.out.println with the newlogger.info.

Modifications are done in the following classes:

AspectClass.java

App.java

Output

Spring AOP – @Around Advice

In the previous example, we have used Logger with around advice. We can also use it with any other advice types.

Facebooktwitterredditpinterestlinkedinmailby feather