Spring AOP: Before Advice

In this article, we will discuss before advice in detail. This is basically intercepted before execution of method/s.

We will implement three different approaches

  • Implements MethodBeforeAdvice interface
  • Using pointcut expression (XML configuration)
  • Using AspectJ Annotations i.e.; (@Aspect / @Before)

Technology Used

  • Java 1.7
  • Eclipse Kepler IDE
  • Maven 3.0.4
  • Spring-4.0.0-RELEASE
  • AspectJ

Mavenize or download required jars

Add Spring-4.0.0 dependencies to the pom.xml

	<!-- Spring dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

	<!-- AspectJ dependencies -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj.version}</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>${org.aspectj.version}</version>
		</dependency>

Folks who aren’t familiar with Maven concepts or don’t require maven for their project, can download the below jars individually from the spring site and include them in the classpath

  • spring-core-4.0.0-RELEASE
  • spring-context-4.0.0-RELEASE
  • spring-beans-4.0.0-RELEASE
  • spring-aop-4.0.0-RELEASE
  • spring-expression-4.0.0-RELEASE
  • commons-logging-1.1.1
  • aopalliance-1.0
  • aspectjrt-1.7.4
  • aspectjweaver-1.7.4

Let’s see coding in action

Create interface & classes for employee with their business methods to be exposed

Employee Service interface

Interface with five methods with simple CRUD like operations for employee bean. All methods inside employee interface are self explanatory.

IEmployeeService.java

package com.spring.series.aop.service;

public interface IEmployeeService {

	// simple CRUD operations for employee service
	public int createEmployee(String employeeDetails);
	public void getEmployee(int employeeId);
	public void updateEmployee(int employeeId);
	public void deleteEmployee(int employeeId);
	public void getAllEmployee();
}

Employee Service Provider class

Implementation of the above employee interface with standard sysout’s to print & study the flow of execution.

EmployeeServiceProvider.java

package com.spring.series.aop.service;

public class EmployeeServiceProvider implements IEmployeeService {

	@Override
	public int createEmployee(String employeeDetails) {
		System.out.println("createEmployee : adds new employee and returns unique employee ID");
		return 0001;
	}

	@Override
	public void getEmployee(int employeeId) {
		System.out.println("getEmployee : list employee details based on the employee ID");
	}

	@Override
	public void updateEmployee(int employeeId) {
		System.out.println("updateEmployee : updates employee details based on the employee ID");
	}

	@Override
	public void deleteEmployee(int employeeId) {
		System.out.println("deleteEmployee : deletes employee based on the employee ID");
	}

	@Override
	public void getAllEmployee() {
		System.out.println("getAllEmployee : lists all employee details");
	}
}

 

Let’s discuss different approaches for before advice

 

Approach 1: Creating advice class implementing standard available interfaces in Spring Framework

Create before advice class implementing org.springframework.aop.MethodBeforeAdvice and one more method for pointcut expression

BeforeAdviceInterceptor.java

package com.spring.series.aop.advice;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

public class BeforeAdviceInterceptor implements MethodBeforeAdvice {

	@Override
	public void before(Method method, Object[] args, Object target) throws Throwable {
		System.out.println("******** MethodBeforeAdvice : " + method.getName() + " ********");
	}

	/**
	 * this is method is invoked from the pointcut expression declared in the spring context xml
	 */
	public void beforeAdviceUsingPointcutExpression() {
		System.out.println("******** Before Advice using Pointcut Expression ********");
	}
}

Create Spring context root xml to declare beans

Three beans declared in the Spring configuration xml file

  • employeeService bean for the target object for which advice needs to be applied
  • beforeAdviceInterceptor bean for before advice
  • employeeServiceProxy bean combining interceptors & target object for AOP proxy mechanism

SpringAOPContext.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

	<!-- target business class -->
	<bean id="employeeService" class="com.spring.series.aop.service.EmployeeServiceProvider" />

	<!-- before advice class -->
	<bean id="beforeAdviceInterceptor" class="com.spring.series.aop.advice.BeforeAdviceInterceptor" />

	<!-- employee proxy -->
	<bean id="employeeServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="proxyInterfaces">
			<list>
				<value>com.spring.series.aop.service.IEmployeeService</value>
			</list>
		</property>
		<property name="interceptorNames">
			<list>
				<value>beforeAdviceInterceptor</value>
			</list>
		</property>
		<property name="target">
			<ref bean="employeeService" />
		</property>
	</bean>

</beans>

Note: Name of the Spring Bean Configuration file can be anything (not necessary to have SpringAOPContext.xml) and it’s your choice. But, in the enterprise application keep these file names appropriate to the business context. So that it will increase the readability of the application

Project Structure in Eclipse (Package Explorer view)

BeforeAdvice

Test the Application that’s exactly …. Run it!

Let’s test using ApplicationContext

TestEmployee.java

package com.spring.series.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.series.aop.service.IEmployeeService;

public class TestEmployee {

	public static void main(String[] args) {
		testAdvice();
	}

	// test using ApplicationContext
	private static void testAdvice(){

		// load the spring xml configuration file from classpath
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/aop/SpringAOPContext.xml");

		// get bean using applicationContext
		IEmployeeService employeeService = (IEmployeeService) applicationContext.getBean("employeeServiceProxy"); // employeeServiceProxy/employeeService

		// invoke business methods of EmployeeService
		employeeService.createEmployee("dummy emp details");
		employeeService.getEmployee(001);
		employeeService.updateEmployee(002);
		employeeService.deleteEmployee(003);
		employeeService.getAllEmployee();
	}
}

Note: getBean() method takes proxy bean as argument and not the target object

Output in console

Aug 03, 2014 8:02:33 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@34469729: startup date [Sun Aug 03 20:02:33 IST 2014]; root of context hierarchy
Aug 03, 2014 8:02:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/spring/series/aop/SpringAOPContext.xml]

******** MethodBeforeAdvice : createEmployee ********
createEmployee : adds new employee and returns unique employee ID

******** MethodBeforeAdvice : getEmployee ********
getEmployee : list employee details based on the employee ID

******** MethodBeforeAdvice : updateEmployee ********
updateEmployee : updates employee details based on the employee ID

******** MethodBeforeAdvice : deleteEmployee ********
deleteEmployee : deletes employee based on the employee ID

******** MethodBeforeAdvice : getAllEmployee ********
getAllEmployee : lists all employee details

This way advice is applied to all business methods of the EmployeeService, but what if we want to restrict the advice should be advised to some of the particular business methods with before advice

Solution: Include <aop:config> tag with pointcut expression defining the regex in the Spring root configuration xml file

Approach 2: Using pointcut expression to limit the advice to be applied to few particular methods 

Updated Spring Configuration file with <aop:config> tag

Pointcut expression: “execution(* com.spring.series.aop.service.*.get(..)”

This pointcut expression narrows the advice to be applied only to the execution of the above methods.

General syntax:

execution(<return_type> <qualified.package.name>.<className>.<methodName>.(<arguments>)

So, below pointcut expression narrows only methods whose methodName starts with get and has any number of arguments inside any class but within package com.spring.series.aop.service

SpringAOPContext.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

	<!-- target business class -->
	<bean id="employeeService" class="com.spring.series.aop.service.EmployeeServiceProvider" />

	<!-- before advice class -->
	<bean id="beforeAdviceInterceptor" class="com.spring.series.aop.advice.BeforeAdviceInterceptor" />

	<aop:config>
		<aop:aspect id="aspect" ref="beforeAdviceInterceptor">
			<aop:pointcut id="pointcutExpression" expression="execution(* com.spring.series.aop.service.*.get*(..))" />
			<aop:before pointcut-ref="pointcutExpression" method="beforeAdviceUsingPointcutExpression" />
		</aop:aspect>
	</aop:config>

</beans>

Let re-run the test class with getBean() method taking target object as argument.

TestEmployee.java

package com.spring.series.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.series.aop.service.IEmployeeService;

public class TestEmployee {

	public static void main(String[] args) {
		testAdvice();
	}

	// test using ApplicationContext
	private static void testAdvice(){

		// load the spring xml configuration file from classpath
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/aop/SpringAOPContext.xml");

		// get bean using applicationContext
		IEmployeeService employeeService = (IEmployeeService) applicationContext.getBean("employeeService"); // employeeServiceProxy/employeeService

		// invoke business methods of EmployeeService
		employeeService.createEmployee("dummy emp details");
		employeeService.getEmployee(001);
		employeeService.updateEmployee(002);
		employeeService.deleteEmployee(003);
		employeeService.getAllEmployee();
	}
}

Output in console

Aug 03, 2014 8:04:59 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6c1961f4: startup date [Sun Aug 03 20:04:59 IST 2014]; root of context hierarchy
Aug 03, 2014 8:04:59 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/spring/series/aop/SpringAOPContext.xml]

createEmployee : adds new employee and returns unique employee ID

******** Before Advice using Pointcut Expression ********
getEmployee : list employee details based on the employee ID

updateEmployee : updates employee details based on the employee ID

deleteEmployee : deletes employee based on the employee ID

******** Before Advice using Pointcut Expression ********
getAllEmployee : lists all employee details

If you see output, before advice is applied to the methods which are starting with get and taking any number of arguments

That’s not all; let’s move onto the next approach

Approach 3: Using AspectJ Annotations i.e.; (@Aspect / @Before)

Business interface and their implementation classes remain the same. Only difference with this approach is that, removing those few lines of configuration from spring configuration xml file and replacing with simple AspectJ annotations

Create a class annotated with @Aspect and advice methods with @Before for before advice

BeforeAdviceAnnotation.java

package com.spring.series.aop.advice;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class BeforeAdviceAnnotation {

	// execution(returnType qualified.package.name.classname.methodname(arguments))

	@Before("execution(* com.spring.series.aop.service.*.get*(..))")
	public void beforeAdviceUsingAnnotation() {
		System.out.println("******** Before Advice using Annotation ********");
	}
}

Note

  • Now advice will be applied only to the methods whose starting name is get,
  • If we replace this “get*” with just wild card character (*) then advice will be applied to all methods of employee service class.

Create Spring context root xml to declare beans and turn on AspectJ annotation

Three beans declared in the Spring configuration xml file

  • employeeService bean for the target object for which advice needs to be applied
  • beforeAdviceAnnotation bean for before advice which is annotated with @Aspect/@Before annotation
  • <aop:aspect-autoproxy> to turn ON AspectJ annotation and automatically creating proxies

SpringAOPContext.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

	<!-- target business class -->
	<bean id="employeeService" class="com.spring.series.aop.service.EmployeeServiceProvider" />

	<!-- to turn aspectJ annotation -->
	<aop:aspectj-autoproxy />

	<!-- before advice using annotation -->
	<bean id="beforeAdviceAspect" class="com.spring.series.aop.advice.BeforeAdviceAnnotation" />

</beans>

Time to test the annotated application example

TestEmployee.java

package com.spring.series.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.series.aop.service.IEmployeeService;

public class TestEmployee {

	public static void main(String[] args) {
		testAdvice();
	}

	// test using ApplicationContext
	private static void testAdvice(){

		// load the spring xml configuration file from classpath
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/spring/series/aop/SpringAOPContext.xml");

		// get bean using applicationContext
		IEmployeeService employeeService = (IEmployeeService) applicationContext.getBean("employeeService"); // employeeServiceProxy/employeeService

		// invoke business methods of EmployeeService
		employeeService.createEmployee("dummy emp details");
		employeeService.getEmployee(001);
		employeeService.updateEmployee(002);
		employeeService.deleteEmployee(003);
		employeeService.getAllEmployee();
	}
}

Output in console

Aug 03, 2014 8:06:14 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@766e119d: startup date [Sun Aug 03 20:06:14 IST 2014]; root of context hierarchy
Aug 03, 2014 8:06:14 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/spring/series/aop/SpringAOPContext.xml]

createEmployee : adds new employee and returns unique employee ID

******** Before Advice using Annotation ********
getEmployee : list employee details based on the employee ID

updateEmployee : updates employee details based on the employee ID

deleteEmployee : deletes employee based on the employee ID

******** Before Advice using Annotation ********
getAllEmployee : lists all employee details

This annotation states that advice annotated with @Before annotation is advised only to the methods whose starting letters are get*(..) inside any class, taking any number of arguments but restricted within package com.spring.series.aop.service as attribute in the @Before annotation

Note: to apply advice to all business methods of the employee service class using AspectJ annotation, remove the restriction with just a simple wildcard character (*) à this way advice is applied to all methods of the employee service class

Download project

Spring-AOP-Before-Advice (4kB)
Spring-AOP-Before-Advice-using-Pointcut (4kB)
Spring-AOP-@Before-Annotation (4kB)

 

Read Also:

 

Happy Coding !!
Happy Learning !!

Spring AOP: After Returning Advice
Spring AOP: Aspect Oriented Programming