Spring AOP

Spring AOP-Ordering of Aspects with Example

In Spring AOP aspects ordering tutorial, we will discuss how to use @Order annotation and Order interface to decide precedence/order of the aspects applied to the same join point. In my last tutorials of Spring AOP advice, you have seen that we have applied single Aspect to a join point. In real time projects, we have to use multiple aspects in our application and these aspects can be applied on a certain method. So in this situation there are more than one aspect applied to the same join point. In this case, the order of execution of the aspects will not be determined unless we have explicitly specified by using either @Order annotation or org.springframework.core.Ordered interface.

 Download Application Source Code
SpringAOP-Aspects-Order-Example from Github.

Let’s see Aspects Ordering with the example. In this example we have three aspects LoggingAspect, SecurityAspect and TransactionAspect for same join point transfer() method of TransferService class in the com.doj.aopapp.service package. Suppose we want to apply these aspects in the following order to the same join point (transfer() target method of TransferSerivce).

  1. SecurityAspect
  2. TransactionAspect
  3. LoggingAspect

So, achieving this order of aspects we using two ways.

  1. @Order Annoation
  2. org.springframework.core.Ordered interface

1. Specifying order by using @Order annotation

This is very simple way. Use the annotation as below.

SecurityAspect.java

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

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
@Order(0)
public class SecurityAspect {
 
 /**
  * Declaring before 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
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****SecurityAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }
}

TransactionAspect.java

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

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
@Order(1)
public class TransactionAspect {
 
 /**
  * Declaring before 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
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****TransactionAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }
 
}

LoggingAspect.java

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

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

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
@Order(2)
public class LoggingAspect {
 
 /**
  * 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 beforeAdviceForTransferMethods(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("****LoggingAspect Before execution of Transfer Methods " + pjp.getSignature().getName());
        pjp.proceed();
        System.out.println("****LoggingAspect After execution of Transfer Methods " + pjp.getSignature().getName());
    }
}

2. Specifying order by using org.springframework.core.Ordered interface

This is also very simple way. Use the interface as below.

SecurityAspect.java

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

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class SecurityAspect implements Ordered{
 
 /**
  * Declaring before 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
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****SecurityAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }

 @Override
 public int getOrder() {
  return 0;
 }
}

TransactionAspect.java

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

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class TransactionAspect implements Ordered{
 
 /**
  * Declaring before 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
  */
 @Before("execution(* com.doj.aopapp.service.*.transfer(*,*,*))")
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****TransactionAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }

 @Override
 public int getOrder() {
  return 1;
 }
 
}

LoggingAspect.java

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

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

/**
 * @author Dinesh.Rajput
 *
 */
@Aspect
@Component
public class LoggingAspect implements Ordered {
 
 /**
  * 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 beforeAdviceForTransferMethods(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("****LoggingAspect Before execution of Transfer Methods " + pjp.getSignature().getName());
        pjp.proceed();
        System.out.println("****LoggingAspect After execution of Transfer Methods " + pjp.getSignature().getName());
    }

 @Override
 public int getOrder() {
  return 2;
 }
}

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 {
 
}

ApplicationContext Configuration file based on XML Config

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <aop:config>
  <aop:aspect ref="securityAspect" order="0">
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:before method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
  <aop:aspect ref="transactionAspect" order="1">
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:before method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
  <aop:aspect ref="loggingAspect" order="2">
   <!-- all public methods whose name are transfer() with taking three arguments of any type and any return type of all classes in the com.doj.aopapp.service package -->
   <aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>
   <aop:around method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
 </aop:config>
 
 <bean id="transferService" class="com.doj.aopapp.service.TransferServiceImpl"/>
 <bean id="securityAspect" class="com.doj.aopapp.aspect.SecurityAspect"/>
<bean id="transactionAspect" class="com.doj.aopapp.aspect.TransactionAspect"/>
 <bean id="loggingAspect" class="com.doj.aopapp.aspect.LoggingAspect"/>
</beans>

Test Class for Spring AspectJ Configuration and Execution

Let’s run the example as below:

/**
 * 
 */
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.transfer("accountA", "accountB", 50000l);
  applicationContext.close();
 }

}

Output on the Console:

Mar 20, 2017 5:59:16 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Mon Mar 20 17:59:16 IST 2017]; root of context hierarchy
****SecurityAspect.beforeAdviceForTransferMethods() transfer
****TransactionAspect.beforeAdviceForTransferMethods() transfer
****LoggingAspect Before execution of Transfer Methods transfer
50000 Amount has been tranfered from accountA to accountB
****LoggingAspect After execution of Transfer Methods transfer
Mar 20, 2017 5:59:17 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6576fe71: startup date [Mon Mar 20 17:59:16 IST 2017]; root of context hierarchy

As per as output on the console Spring AOP aspects ordering is working as expected.

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago