dineshonjava

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.

Spring AOP Related Posts
  1. Spring AOP Interview Questions and Answers
  2. Spring AOP Tutorial- Aspect Oriented Programming with Spring
  3. @Aspect Annotation in Spring
  4. Advices in Spring AOP
  5. Spring AOP JoinPoints and Advice Arguments
  6. Spring AOP Pointcuts and Wildcard Expressions
  7. Spring AOP XML configuration
  8. Spring AOP XML Schema based Example
  9. Spring AOP AspectJ @Before Annotation Advice Example
  10. Spring AOP Before Advice Example using XML Config
  11. Spring AOP AspectJ @After Annotation Advice Example
  12. Spring AOP After Advice Example using XML Config
  13. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  14. Spring AOP After-Returning Advice Example using XML Config
  15. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  16. Spring AOP After Throwing Advice Example using XML Config
  17. Spring AOP AspectJ @Around Annotation Advice Example
  18. Spring AOP Around Advice Example using XML Config
  19. Spring AOP Writing First AspectJ Program in Spring
  20. Spring AOP Proxies in Spring
  21. Spring AOP Transaction Management in Hibernate
  22. Spring Transaction Management
  23. Spring Declarative Transaction Management Example