Spring AOP AspectJ @Around Annotation Advice Example

In this spring aop Around advice example, we will learn how to use aspectj @Around annotation with java configuration. In Spring AOP, Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception i.e a method which annotated with AspectJ @Around annotation run before and after any matching pointcut expression, advised method execution.

 Download Application Source Code

Spring AOP AspectJ @Around Annotation Advice Example from GitHub.

Let’s create a simple spring application and add logging aspect to be invoked every joint point in the service class in the application. This example is also available with XML configuration in the application Spring AOP Around Advice Example.

AspectJ @Around Annotation

@Around annotation is an Aspectj annotation, it is not Spring AOP annotation, so we have to add Aspectj maven dependency with Spring AOP in this example. Let’s see our LoggingAspect class with Around advice annotation.

 

/**
 * 
 */
package com.doj.aopapp.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class LoggingAspect {
 
 /**
  * Declaring around advice 
  * @param jp
  * @throws Throwable
  */
 //@Around("execution(* com.doj.aopapp.service.*.*(..))") // around advice with pointcut expression directly
 @Around("logForAllMethods()") //around advice with name pointcut that declared as name logForAllMethods()
 public void aroundAdviceForAllMethods(ProceedingJoinPoint jp) throws Throwable {
  System.out.println("****Before advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForAllMethods()");
        jp.proceed();
        System.out.println("****After advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForAllMethods()" );
        System.out.println();
    }
 
 /**
  * Declaring around advice for all transfer methods whose taking three arguments of any type 
  * of all classes in the package com.doj.aopapp.service
  * @param jp
  * @throws Throwable
  */
 @Around("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void aroundAdviceForTransferMethods(ProceedingJoinPoint jp) throws Throwable {
  System.out.println("****Before advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForTransferMethods()");
        jp.proceed();
        System.out.println("****After advised method execution "+jp.getSignature().getName()+" LoggingAspect.aroundAdviceForTransferMethods()" );
        System.out.println();
    }
 
 /**
  * Declaring named pointcut
  */
 @Pointcut("execution(* com.doj.aopapp.service.*.*(..))")
 public void logForAllMethods(){}
}

Note: Around advice is special type of advice in the Spring AOP and it has capacity to modify the return of advised method and has full to invoke advised method. And never forget to use ProceedingJoinPoint as parameter and must call ProceedingJoinPoint.proceed(); method, else the advised method will never be executed.

Declare Pointcut expressions

#1. In this expression, We have declared around advice, it is valid for all public methods with any number arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

@Around("execution(* com.doj.aopapp.service.*.*(..))")

#2. In this expression, We have declared around advice, it is valid for all public methods whose name is transfer() with taking three arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

@Around("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")

Spring AOP AspectJ @Around Annotation Example

Now let’s see complete example of Spring AOP aspectj @Around annotation.

Spring AOP and AspectJ Maven Dependencies

<properties>
   <spring.version>4.3.7.RELEASE</spring.version>
   <aspectj.version>1.8.9</aspectj.version>
  </properties>
  
  <dependencies>
   <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context-support</artifactId>
         <version>${spring.version}</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>${spring.version}</version>
     </dependency>
     
     <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjrt</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
      <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>${aspectj.version}</version>
      </dependency>
  </dependencies>

ApplicationContext Configuration file based on Java Config

AppConfig.java

/**
 * 
 */
package com.doj.aopapp.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

/**
 * @author Dinesh.Rajput
 *
 */
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages={"com.doj.aopapp.aspect", "com.doj.aopapp.service"})
public class AppConfig {
 
}

#1. Enabling @AspectJ using @EnableAspectJAutoProxy Annotation:

Spring AOP provides an annotation to enable @AspectJ support in the application. By default spring framework doesn’t create any proxy for any advice, so we have to enable by using @EnableAspectJAutoProxy annotation.

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {

}

#2. Enabling @AspectJ using <aop:aspectj-autoproxy/> in XML Configuration:

<aop:aspectj-autoproxy/> namespace is equivalent to @EnableAspectJAutoProxy annotation to enable @AspectJ support in the application in XML configuration. Let’s see how to use this namespace <aop:aspectj-autoproxy/>.

<!-- Enable @AspectJ annotation support  -->
    <aop:aspectj-autoproxy/>

Target method of Service class on which aspects needs to apply

TransferService.java

/**
 * 
 */
package com.doj.aopapp.service;

/**
 * @author Dinesh.Rajput
 *    
 */
public interface TransferService {
 
 void transfer(String accountA, String accountB, Long amount);
 
 Double checkBalance(String account);
 
 Long withdrawal(String account, Long amount);
 
 void diposite(String account, Long amount);
}

TransferServiceImpl.java

/**
 * 
 */
package com.doj.aopapp.service;

import org.springframework.stereotype.Service;

/**
 * @author Dinesh.Rajput
 *
 */
@Service
public class TransferServiceImpl implements TransferService {

 @Override
 public void transfer(String accountA, String accountB, Long amount) {
  System.out.println(amount+" Amount trasferring from "+accountA+" to "+accountB);
 }

 @Override
 public Double checkBalance(String account) {
  System.out.println("Available balance: 50000");
  return new Double(50000);
 }

 @Override
 public Long withdrawal(String account, Long amount) {
  System.out.println("Withdrawal amount: " +amount);
  return amount;
 }

 @Override
 public void diposite(String account, Long amount) {
  System.out.println(amount+" Amount has been diposited to "+account);
 }

}

Aspect class:

LoggingAspect.java as given above in this tutorial.

Test Class for Spring AspectJ Configuration and Execution

Let’s execute following test class and analyse the output on the console.

/**
 * 
 */
package com.doj.aopapp.test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.doj.aopapp.config.AppConfig;
import com.doj.aopapp.service.TransferService;

/**
 * @author Dinesh.Rajput
 *
 */
public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
  TransferService transferService = applicationContext.getBean(TransferService.class);
  transferService.checkBalance("accountA");
  transferService.transfer("accountA", "accountB", 50000l);
  transferService.diposite("accountA",  50000l);
  transferService.withdrawal("accountB", 40000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 09, 2017 11:49:10 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Mar 09 23:49:10 IST 2017]; root of context hierarchy
****Before advised method execution checkBalance LoggingAspect.aroundAdviceForAllMethods()
Available balance: 50000
****After advised method execution checkBalance LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution transfer LoggingAspect.aroundAdviceForAllMethods()
****Before advised method execution transfer LoggingAspect.aroundAdviceForTransferMethods()
50000 Amount trasferring from accountA to accountB
****After advised method execution transfer LoggingAspect.aroundAdviceForTransferMethods()

****After advised method execution transfer LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution diposite LoggingAspect.aroundAdviceForAllMethods()
50000 Amount has been diposited to accountA
****After advised method execution diposite LoggingAspect.aroundAdviceForAllMethods()

****Before advised method execution withdrawal LoggingAspect.aroundAdviceForAllMethods()
Withdrawal amount: 40000
****After advised method execution withdrawal LoggingAspect.aroundAdviceForAllMethods()

Mar 09, 2017 11:49:10 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Thu Mar 09 23:49:10 IST 2017]; root of context hierarchy

As output of above console, every log messages has been executed before and after advised method execution.

Project Structure

Spring AOP AspectJ @Around Annotation Advice Example

 

Spring AOP Related Posts

 

 

Previous
Next