Spring AOP – @Around Advice

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

import java.util.concurrent.TimeUnit;
 import org.springframework.stereotype.Component;
 @Component
 public class Service {
                 public String delay() {
                                 // produce a delay
                                 try {
                                                 TimeUnit.SECONDS.sleep(10);
                                     } catch (InterruptedException e) {
                                       e.printStackTrace();
                                 }
                                 return " Delay in seconds " ;
                 }
  } 
  • 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

import org.springframework.context.annotation.ComponentScan;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 @Configuration
 @EnableAspectJAutoProxy
 @ComponentScan( "com.app.SpringAOP_Around" )
 public class DemoAOP {
 } 
  • 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

import java.util.List;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.springframework.stereotype.Component;
 @Aspect
 @Component
 public class AspectClass {
                 @Around(" execution( * com.app.SpringAOP_Around.*.*()) ")
                 public Object aroundServiceMehod(ProceedingJoinPoint pjp) throws Throwable { 
                                 String str = pjp.getSignature().toShortString();
                                 System.out.println(" \n Executing the @Around advice on method : " + str);
                                 // begin the TimeStamp
                                 long start = System.currentTimeMillis();
                                 // execute the method
                                 Object reslt = pjp.proceed();
                                 // end the stopwatch
                                 long end = System.currentTimeMillis(); 
                                 // compute the result
                                 long duration = end - start;
                                 System.out.println(" \n The Total Duration is :" + duration / 1000.0 + "seconds");
                                 return reslt;
                 }
  } 
  • Create the main class

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

App.java

import java.util.List;
 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 public class App 
 {
     public static void main( String[] args )
     {
         AnnotationConfigApplicationContext appcontext = new AnnotationConfigApplicationContext( DemoAOP.class );
        Service serve = appcontext.getBean( "service", Service.class );
         System.out.println(" Main Program - @Around"); 
         System.out.println(" callling the delay method");
         String s = serve.delay();
         System.out.println(" \n Message is :" + s);
         System.out.println("done");
         appcontext.close();
          }
  } 

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:

     private static Logger newlogger = Logger.getLogger(App.class.getName()); 

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

import java.util.List;
 import java.util.logging.Logger;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.springframework.stereotype.Component;
 @Aspect
 @Component
 public class AspectClass {
                 private Logger newlogger = Logger.getLogger(getClass().getName());
                 @Around(" execution( * com.app.SpringAOP_Around.*.*()) ")
                 public Object aroundServiceMehod(ProceedingJoinPoint pjp) throws Throwable {
                                 String str = pjp.getSignature().toShortString();
                                 newlogger.info(" \n Executing the @Around advice on method : " + str);
                                 // begin the TimeStamp
                                 long start = System.currentTimeMillis();
                                 // execute the method
                                 Object reslt = pjp.proceed();
                                 // end the stopwatch
                                 long end = System.currentTimeMillis(); 
                                 // compute the result
                                 long duration = end - start;
                                 newlogger.info(" \n The Total Duration is :" + duration / 1000.0 + "seconds");
                                 return reslt;
                 }
  } 

App.java

import java.util.List;
 import java.util.logging.Logger;
 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 public class App 
 {
      private static Logger newlogger = Logger.getLogger(App.class.getName()); 
      public static void main( String[] args )
     {
         AnnotationConfigApplicationContext appcontext = new AnnotationConfigApplicationContext(DemoAOP.class);
        Service serve = appcontext.getBean( "service", Service.class);
        newlogger.info(" Main Program - @Around");
        newlogger.info(" callling the delay method");
        String s = serve.delay();
        newlogger.info(" \n Message is :" + s);
        newlogger.info(" done ");
         appcontext.close();
        }
  } 

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.


Related Topics

Spring - Bean Scopes with Annotations

Spring - Bean Scopes with Annotations We have previously discussed the Spring bean scopes using an XML-based configuration. In the XML-based configuration, we have defined the beans and its scope inside the bean-config...

3 minutes read.

Spring MVC Form Checkbox

Spring MVC provides several form tags used to develop web applications (Usually JSP pages). One of them is a checkbox tag. The checkbox tag offers us to choose multiple options at the same...

12 minutes read.

Spring - Injecting values from Property Files

Spring - Injecting values from Property Files In this section, we will discuss how to inject values from a property file using the Java-based configuration. Here, we will use two annotations @Value and @PropertySource...

3 minutes read.

Spring MVC Tutorial

Spring MVC is a web Model-View-Controller framework built on Servlet API. It is used to build web applications. The MVC framework works around central servlet called DispatcherServlet. It dispatches the requests to the...

4 minutes read.

Spring AOP – @After Advice

Spring AOP – @After Advice We have previously discussed the concepts of Spring AOP. One of the AOP concepts is Advice, which is further divided into various types. After (finally) is a type of advice...

3 minutes read.

Spring MVC Regular Expression Validation

Example of Regular Expression Validation Here, we are going to create an example of regular expression validation. Following are the steps to create an example of a regular expression: Create a request page In this step, we are going...

13 minutes read.

Spring - Bean lifecycle using annotations

Spring - Bean lifecycle using annotations We have already discussed the bean lifecycle using an XML-based configuration. In the previous case, we have declared the init-method and destroy-method attributes in the bean-configuration file. Here, we...

2 minutes read.

Spring – Beans using @Bean

Spring – Beans using @Bean We have previously discussed an example of Spring configuration using an XML-based configuration. In the previous example, we have defined beans inside the bean-configuration file (applicationContext.xml). To make the...

3 minutes read.

Spring MVC Form Tag Library

The Spring MVC provides a variety of tags available in the form of a tag library, which is used to develop web pages (JSP view pages). The Spring’s form tag...

6 minutes read.

Spring MVC Number Range Validation

Example of Number Range Validation Here, we are going to create an example of number range validation. Following are the steps to create an example of number range validation. Create a request page In this step, we are...

12 minutes read.

Spring Autowiring – Setter Injection

Spring Autowiring – Setter Injection We have previously discussed an example of Setter Dependency Injection (SDI) using an XML file. In the previous case, we have defined the property name for the dependency...

2 minutes read.

Spring AOP – Pointcut Expressions

Spring AOP – Pointcut Expressions Pointcut refers to a collection of join points that specify where advice to be applied. In other words, pointcut represents a set of various join points. It defines that...

7 minutes read.

Spring Model Interface

Model Interface Model is an interface that defines a holder for model attributes. It is also used to transfer data between various parts of the Spring MVC application. The Model interface is available...

8 minutes read.

Spring – Configuration using @Configuration

Spring – Configuration using @Configuration We have previously discussed the Spring configuration using an XML configuration file. In that case, we have defined all the bean information in the bean-configuration file (applicationContext.xml). ...

3 minutes read.

Spring Framework Annotations

Spring Framework Annotations Spring framework provides a variety of annotations for a better approach. Using annotations, we can develop Spring applications (small & large scale) easily with less code. Following are the annotations...

6 minutes read.

Spring – Bean Lifecycle

Spring – Bean Lifecycle Spring bean is responsible for managing the lifecycle of beans created by the Spring container.  The lifecycle of the bean is easy to understand. When a bean is created, it requires...

4 minutes read.

Spring AOP – @Around Advice

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...

4 minutes read.

Spring AOP – @Before Advice Type

Spring AOP – @Before Advice Type As we have discussed, AOP (Aspect-Oriented Programming) is one of the powerful features of the Spring framework. It complements the Object-Oriented Programming (OOPs). AOP provides some concepts and terminology,...

2 minutes read.

Spring Autowiring –Field Injection

Spring Autowiring –Field Injection The Field Injection is used to inject the fields, variables, or properties of the beans. It is not available in autowiring using XML- based configuration. It is a...

2 minutes read.

Spring – Annotation-based Inversion of Control (IoC)

Spring – Annotation-based Inversion of Control (IoC) We have previously discussed an example of Spring IoC (Inversion of Control). In the previous case, we have used the bean-configuration file to define the bean...

3 minutes read.