Spring AOP

Spring AOP Before Advice Example using XML Config

In this spring aop before advice example based on XML configuration, we learn how to use Spring AOP before advice using <aop:before/> XML configuration. In Spring AOP Before Advice is that executes before a join point i.e Any methods configured as before advice always run immediately before the target methods which match the pointcut expression.

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

Configuring Spring AOP Before Advice using aop namespace <aop:before/> and <aop:config>

In this example, we are using <aop:*/> namespace of XML configuration spring framework. We have to add aop namespace in the XML configuration file for application context for <aop:before/> advice in this application. Let’s see our aop configuration for before advice in this example.

 

<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:before method="beforeAdviceForAllMethods" pointcut-ref="logForAllMethods"/>
 <aop:before method="beforeAdviceForTransferMethods" pointcut-ref="logForAllTransfer"/>
    </aop:aspect>
</aop:config>

Pointcut expressions

1. Following pointcut expression for before advice is valid for 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"/>

2. Following pointcut expression for before advice is valid for 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"/>

Spring AOP Before Advice Example

Let’s create an example for a before advice, using xml configuration using <aop:before/> 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:before method="beforeAdviceForAllMethods" pointcut-ref="logForAllMethods"/>
   <aop:before method="beforeAdviceForTransferMethods" 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>

<aop:config/> element
A section (compartmentalization) of AOP-specific configuration (including aspects, pointcuts, etc).

<aop:aspect/> element
A named aspect definition.

<aop:pointcut/> element
A named pointcut definition.

<aop:before/> element
A before advice definition.

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 void transfer(String accountA, String accountB, Long amount) {
  System.out.println(amount+" Amount has been tranfered from "+accountA+" to "+accountB);
 }

 @Override
 public Double checkBalance(String account) {
  return new Double(50000);
 }

 @Override
 public Long withdrawal(String account, Long amount) {
  return amount;
 }

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

}

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

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

import org.aspectj.lang.JoinPoint;

/**
 * @author Dinesh.Rajput
 *
 */
public class LoggingAspect {
 
 /**
  * Declaring before advice 
  * @param jp
  * @throws Throwable
  */
 public void beforeAdviceForAllMethods(JoinPoint jp) throws Throwable {
        System.out.println("****LoggingAspect.beforeAdviceForAllMethods() " + jp.getSignature().getName());
    }
 
 /**
  * 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
  */
 public void beforeAdviceForTransferMethods(JoinPoint jp) throws Throwable {
        System.out.println("****LoggingAspect.beforeAdviceForTransferMethods() " + jp.getSignature().getName());
    }
}

Test Class for Spring AOP Before Advice Configuration and Execution

Now let’s see how to run and what would be output of this application when above configured aspects execute on given pointcut information.

/**
 * 
 */
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);
  System.out.println("Available balance: " +transferService.checkBalance("accountA"));
  transferService.diposite("accountA",  50000l);
  System.out.println("Withdrawal amount: " +transferService.withdrawal("accountB", 40000l));
  applicationContext.close();
 }

}

Output on the Console:

Mar 07, 2017 6:55:52 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Tue Mar 07 18:55:52 IST 2017]; root of context hierarchy
Mar 07, 2017 6:55:52 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
****LoggingAspect.beforeAdviceForAllMethods() transfer
****LoggingAspect.beforeAdviceForTransferMethods() transfer
50000 Amount has been tranfered from accountA to accountB
****LoggingAspect.beforeAdviceForAllMethods() checkBalance
Available balance: 50000.0
****LoggingAspect.beforeAdviceForAllMethods() diposite
50000 Amount has been diposited to accountA
****LoggingAspect.beforeAdviceForAllMethods() withdrawal
Withdrawal amount: 40000
Mar 07, 2017 6:55:52 PM org.springframework.context.support.ClassPathXmlApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Tue Mar 07 18:55:52 IST 2017]; root of context hierarchy

Analyse the output, all join points execute with given information in this example.

Project Structure

Application Source Code

Spring AOP Before Advice Example using XML Config on GitHub.

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