Spring AOP Around Advice Example using XML Config

In this spring aop example of around advice with XML configuration, we learn how to use Spring AOP Around advice using <aop:around/> XML namespace  configuration. In Spring AOP, Around Advice to be executed if a method exits by throwing an exception i.e  Any methods configured as Around advice always run immediately after the target methods throws any exception.

Download Application Source Code

Spring AOP Around Advice Example using XML Config on GitHub.

Let’s create a simple spring application and add logging aspect to be invoked on based on pointcuts information passed in <aop:around/> xml configuration. This example is also available with Java configuration Spring AOP AspectJ @Around Annotation Advice Example.

Configuring Spring AOP After Throwing Advice using aop namespace <aop:around/>
In this example, we are using <aop:*/> namespace for XML configuration. So here we have to add <aop:around/> aop namespace in our XML configuration file in this example. Let’s see our aop configuration for after advice in this example.

Let’s create a simple spring application and add logging aspect to be invoked on based on pointcuts information passed in <aop:around/> xml configuration.

<aop:config>
  <aop:aspect ref="loggingAspect">
    <!-- all public methods with any 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.*.*(..))" id="logForAllMethods"/>
    <!-- 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="aroundAdviceForAllMethods" pointcut-ref="logForAllMethods"/>
    <aop:around method="aroundAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
</aop:config>

Declaring Pointcut expressions
#1. In First pointcut expression, we have declared after throwing advice, it is valid for all public methods with any number of arguments of any type and any return type, for all classes in the com.doj.aopapp.service package.

<aop:pointcut expression="execution(* com.doj.aopapp.service.*.*(..))" id="logForAllMethods"/>

#2. In Second pointcut expression, we have declared after throwing 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.

<aop:pointcut expression="execution(* com.doj.aopapp.service.*.transfer(*,*,*))" id="logForAllTransfer"/>

Spring AOP Around Advice Example
Let’s create an example for a Around advice, using xml configuration using <aop:around/> namespace.

Spring AOP 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 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="loggingAspect">
   <!-- all public methods with any 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.*.*(..))" id="logForAllMethods"/>
   <!-- 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="aroundAdviceForAllMethods" pointcut-ref="logForAllMethods"/>
   <aop:around method="aroundAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
  </aop:aspect>
 </aop:config>
 
 <bean id="transferService" class="com.doj.aopapp.service.TransferServiceImpl"/>
 
 <bean id="loggingAspect" class="com.doj.aopapp.aspect.LoggingAspect"/>
</beans>


Aspect class “LoggingAspect”:
Write aspect class and methods to be executed as advice.
LoggingAspect.java

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

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Pointcut;

/**
 * @author Dinesh.Rajput
 *
 */
public class LoggingAspect {
 
 /**
  * Declaring around advice 
  * @param jp
  * @throws Throwable
  */
 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
  */
 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(){}
}

The advice method will have a method argument of type ProceedingJoinPoint which can be used call advised method.

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;

/**
 * @author Dinesh.Rajput
 *
 */
public class TransferServiceImpl implements TransferService {
 
 @Override
 public Double checkBalance(String account) {
  System.out.println("Available balance: 50000");
  return new Double(50000);
 }
 
 @Override
 public void transfer(String accountA, String accountB, Long amount) {
  System.out.println(amount+" Amount trasferring from "+accountA+" to "+accountB);
 }

 @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);
 }

}

Test Class for Spring AOP Around Advice 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.support.ClassPathXmlApplicationContext;

import com.doj.aopapp.service.TransferService;

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

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

}

Output on the Console:

Mar 10, 2017 12:35:29 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Fri Mar 10 00:35:29 IST 2017]; root of context hierarchy
Mar 10, 2017 12:35:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
****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 checkBalance LoggingAspect.aroundAdviceForAllMethods()
Available balance: 50000
****After advised method execution checkBalance 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 10, 2017 12:35:30 AM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Fri Mar 10 00:35:29 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 Around Advice Example using XML Config

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 Writing First AspectJ Program in Spring
  19. Spring AOP Proxies in Spring
  20. Spring AOP Transaction Management in Hibernate
  21. Spring Transaction Management
  22. Spring Declarative Transaction Management Example