Theodora Fragkouli

About Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis.

Spring AOP AspectJ Example

This is a tutorial of how to use AspectJ style support in order to intergrate Aspect Oriented Programming in Spring framework. AOP is used in the Spring Framework to provide declarative enterprise services, especially as a replacement for EJB declarative services. It is also used to allow users to implement custom aspects, complementing their use of OOP with AOP. Spring supports the @AspectJ annotation style approach and the xml-based approach to implement custom aspects. @AspectJ refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations, whereas in xml-based approach aspects are implemented using regular classes along with XML based configuration. We shall show you how to implement all types of aspects using both approaches.

Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New-Maven-Project

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.

Maven-Project-Name-Location

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample". The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample". Hit “Finish” to exit the wizard and to create your project.

Configure-Maven-Project

The Maven project structure is shown below:

Maven-project-structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add Spring 3.2.3 dependency

  • Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
    Create a new property with name org.springframework.version and value 3.2.3.RELEASE.
  • Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page):
    Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}

Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below:
 
pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<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>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.

3. Add AOP AspectJ dependencies

Add the Spring AOP AspectJ dependencies in Maven’s pom.xml file, in order to enable AspectJ, as shown below:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javacodegeeks.snippets.enterprise</groupId>
	<artifactId>springexample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<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>3.2.4.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.5.4</version>
		</dependency>

		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.5.4</version>
		</dependency>

	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>
</project>

4. AspectJ using annotations

In order to begin with the annotation-based approach of AspectJ, we first create a simple bean, simpleServiceBean. Specifically, we create an interface, SimpleService.java and its implementation, SimpleServiceImpl.java. The simpleServiceBean consists of a few methods that will be intercepted by AspectJ.

SimpleService.java

package com.javacodegeeks.snippets.enterprise;

public interface SimpleService {
	
	public void printNameId();

	public void checkName();

	public String sayHello(String message);

}

SimpleServiceImpl.java

package com.javacodegeeks.snippets.enterprise.impl;

import com.javacodegeeks.snippets.enterprise.SimpleService;

public class SimpleServiceImpl implements SimpleService {

	private String name;

	private int id;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public void printNameId() {
		System.out.println("SimpleService : Method printNameId() : My name is " + name
			 + " and my id is " + id);
	}

	public void checkName() {
		if (name.length() < 20) {
			throw new IllegalArgumentException();
		}
	}

	public String sayHello(String message){
		System.out.println("SimpleService : Method sayHello() : Hello! " + message);
		return message;
	}
}

Now, in order to continue, we will create all kinds of aspects, using the annotations provided by AspectJ to intercept the bean's methods. Aspects (classes annotated with @Aspect) may have methods and fields just like any other class. They may also contain pointcut, advice, and introduction (inter-type) declarations. In order to define that a class is an aspect we must annotate it with the @Aspect annotation. The annotations provided by AspectJ to define what kind of advices the aspect should have are:

  1. @Before
  2. @After
  3. @AfterReturning
  4. @AfterThrowing
  5. @Around

4.1 @Before

The @Before annotation is used to define a Before advice in an aspect. The Before advice is the action taken before reaching a specified join point. The join point is a point during the execution of a program, such as the execution of a method or the handling of an exception. The pointcut expression associated to the Advice must match the join point, so that the advice action is taken. The pointcut expression may be either a simple reference to a named pointcut, or a pointcut expression declared in place. The class below is an aspect that has a Before advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..) method will be intercepted:

DoBeforeAspect.java

package com.javacodegeeks.snippets.enterprise.aspect;

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

@Aspect
public class DoBeforeAspect {

	@Before("execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))")
	public void doBefore(JoinPoint joinPoint) {

		System.out.println("***AspectJ*** DoBefore() is running!! intercepted : " + joinPoint.getSignature().getName());
	}

}

The definition of the aspect's bean must be included in applicationContext.xml file, along with the simpleServiceBean definition. Note that in order to enable @AspectJ support we must use the aop:aspectj-autoproxy element.

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<aop:aspectj-autoproxy />
	
	<bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>
 
	<bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
 
</beans>

Now, we load the simpleServiceBean in App.java class and invoke its methods.

App.java

package com.javacodegeeks.snippets.enterprise;

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

public class App {

	public static void main(String[] args) {
	
			ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
			SimpleService simpleService = (SimpleService) context.getBean("simpleServiceBean");
			simpleService.printNameId();
			System.out.println("---------------");
			try{
				simpleService.checkName();
			} catch(Exception e){
				System.out.println("SimpleService checkName() : Exception thrown..");
			}
			System.out.println("---------------");
			simpleService.sayHello("Javacodegeeks");
			System.out.println("---------------");
			context.close();
	}
}

After running the App.java class we see that the sayHello() method of simpleServiceBean is intercepted by the DoBeforeAspect.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
---------------

4.2 @After

The @After annotation is used to define an After advice in an aspect. The After advice is the action taken after reaching a specified join point. For example, if the join point represents a method execution, the After advice will be executed after the method returns either normally or exceptionally. The class below is an aspect that has an After advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..) method will be intercepted again:

DoAfterAspect.java

package com.javacodegeeks.snippets.enterprise.aspect;

	import org.aspectj.lang.JoinPoint;
	import org.aspectj.lang.annotation.Aspect;
	import org.aspectj.lang.annotation.After;
	 
	@Aspect
	public class DoAfterAspect {
	 
		@After("execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))")
		public void doAfter(JoinPoint joinPoint) {
	 
			System.out.println("***AspectJ*** DoAfter() is running!! intercepted : " + joinPoint.getSignature().getName());
	 
		}
	 
	}

The new bean is also defined in applicationContext.xml.

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<aop:aspectj-autoproxy />
	
	<bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>
 
	<bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
	
	<bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
 
</beans>

After running the App.class again, we can see that the sayHello() method is now intercepted by both aspects:

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

4.3 @AfterReturning

The @AfterReturning annotation is used to define an AfterReturning advice in an aspect. The AfterReturning advice is the action taken after reaching a specified join point. For example, if the join point represents a method execution, the AfterReturning advice will be executed after the method returns either normally. The class below is an aspect that has an AfterReturning advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..) method will be intercepted again:

DoAfterReturningAspect.java

package com.javacodegeeks.snippets.enterprise.aspect;

	import org.aspectj.lang.JoinPoint;
	import org.aspectj.lang.annotation.Aspect;
	import org.aspectj.lang.annotation.AfterReturning;
	 
	@Aspect
	public class DoAfterReturningAspect {
	 
	   @AfterReturning(
	      pointcut = "execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))", returning= "result")
	   public void doAfterReturning(JoinPoint joinPoint, Object result) {
	 
		System.out.println("***AspectJ*** DoAfterReturning() is running!! intercepted : " + joinPoint.getSignature().getName());
		System.out.println("Method returned value is : " + result);
	 
	   }
	 
	}

Again, the new bean is defined in applicationContext.xml.

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<aop:aspectj-autoproxy />
	
	<bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>
 
	<bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
	
	<bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
	
	<bean id="doAfterReturningAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
 
</beans>

Now, after running the example again, we can see that the sayHello() method is intercepted by the new AfterReturning aspect too, since it returns normally.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : Javacodegeeks
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

4.4 @AfterThrowing

The @AfterThrowing annotation is used to define an AfterThrowing advice in an aspect. The AfterThrowing advice is the action taken after reaching a specified join point. For example, if the join point represents a method execution, the AfterThrowing advice will be executed after the method throws an exception. The class below is an aspect that has an AfterThrowing advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.checkName() method will be intercepted. This method throws an exception:

DoAfterThrowingAspect.java

package com.javacodegeeks.snippets.enterprise.aspect;

	import org.aspectj.lang.JoinPoint;
	import org.aspectj.lang.annotation.Aspect;
	import org.aspectj.lang.annotation.AfterThrowing;
	 
	@Aspect
	public class DoAfterThrowingAspect {
	 
	   @AfterThrowing(
	      pointcut = "execution(* com.javacodegeeks.snippets.enterprise.SimpleService.checkName(..))",
	      throwing= "error")
	    public void doAfterThrowing(JoinPoint joinPoint, Throwable error) {
	 
		System.out.println("***AspectJ*** DoAfterThrowing() is running!! intercepted : " + joinPoint.getSignature().getName());
		System.out.println("Exception : " + error);
		System.out.println("******");
	 
	    }
	}

The new bean is defined in applicationContext.xml.

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<aop:aspectj-autoproxy />
	
	<bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>
 
	<bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
	
	<bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
	
	<bean id="doAfterReturningAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
 
 	<bean id="doAfterThrowingAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />
 	
</beans>

Now, after running App.java class again, we see that the new aspect intercepts the checkName() method.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
***AspectJ*** DoAfterThrowing() is running!! intercepted : checkName
Exception : java.lang.IllegalArgumentException
******
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : Javacodegeeks
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

4.5 @Around

The @AfterThrowing annotation is used to define an AfterThrowing advice in an aspect. The AfterThrowing advice is the action taken after reaching a specified join point. For example, if the join point represents a method execution, the AfterThrowing advice will be executed after the method throws an exception. The class below is an aspect that has an AfterThrowing advice.

The @Around annotation is used to define an Around advice in an aspect. The Around advice is the action that can actually surround a specified join point, for example it can be executed before or after a method invocation. The class below is an aspect that has an Around advice. It uses a pointcut expression declaring that the com.javacodegeeks.snippets.enterprise.SimpleService.sayHello() method will be intercepted. This method throws an exception:

DoAroundAspect.java

package com.javacodegeeks.snippets.enterprise.aspect;

import java.util.Arrays;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;

@Aspect
public class DoAroundAspect {

	@Around("execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))")
	public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {

		System.out.println("***AspectJ*** DoAround() is running!! intercepted : " +  joinPoint.getSignature().getName()
		+ " \narguments : "	+ Arrays.toString(joinPoint.getArgs()));

		System.out.println("***AspectJ*** DoAround() before is running!");
		joinPoint.proceed(); // continue on the intercepted method
		System.out.println("***AspectJ*** DoAround() after is running!");

	}

}

The new bean is defined in applicationContext.xml file:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<aop:aspectj-autoproxy />
	
	<bean id="simpleServiceBean" class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>
 
	<bean id="doBeforeAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />
	
	<bean id="doAfterAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />
	
	<bean id="doAfterReturningAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />
 
 	<bean id="doAfterThrowingAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />
 	
 	<bean id="doAroundAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAroundAspect" />
 	
</beans>

Now, after running the application again we can see that the sayHello() method is also intercepted by the around advice.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
***AspectJ*** DoAfterThrowing() is running!! intercepted : checkName
Exception : java.lang.IllegalArgumentException
******
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
***AspectJ*** DoAround() is running!! intercepted : sayHello 
arguments : [Javacodegeeks]
***AspectJ*** DoAround() before is running!
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAround() after is running!
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : null
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

5. AspectJ using xml-configuration

Now, we shall see how all above steps can be implemented without using annotations. The XML-based approach of using AspectJ also provides all types of advices. Each aspect in this case is simply a regular Java object defined as bean in applicationContext.xml. The state and behavior of the aspect is captured in the fields and methods of the object, and the pointcut and advice information is captured in the applicationContext.xml. An aspect is declared using the <aop:aspect> element, and the backing bean is referenced using the ref attribute. A named pointcut is declared using the <aop:pointcut> element inside the <aop:aspect> element. It holds two attributes, the id, whose value is a given name of the pointcut and the expression, whose value is the pointcut expression. Both aspects and pointcuts are declared inside the <aop:config> element.

5.1 <aop:before>

The <aop:before> element is used inside the <aop:aspect> element to declare a Before aspect. It has two attributes, the method whose value is the name of the advice method, and the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="simpleServiceBean"
		class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>

	<bean id="doBeforeAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />

		<aop:aspect id="aspects" ref="doBeforeAspect">

			<aop:pointcut id="pointCutBefore"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />

			<aop:before method="doBefore" pointcut-ref="pointCutBefore" />

		</aop:aspect>

	</aop:config>

</beans>

5.2 <aop:after>

The <aop:after> element is used inside the <aop:aspect> element to declare an After aspect. It also has two attributes, the method whose value is the name of the advice method, and the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="simpleServiceBean"
		class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>

	<bean id="doBeforeAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />

	<bean id="doAfterAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />

	<aop:config>
		<aop:aspect id="aspects" ref="doBeforeAspect">
			<aop:pointcut id="pointCutBefore"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:before method="doBefore" pointcut-ref="pointCutBefore" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAfterAspect">
			<aop:pointcut id="pointCutAfter"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after method="doAfter" pointcut-ref="pointCutAfter" />
		</aop:aspect>

	</aop:config>

</beans>

5.3 <aop:after-returning>

The <aop:after-returning> element is used inside the <aop:aspect> element to declare an AfterReturning aspect. It has three attributes. The first attribute is the method, whose value is the name of the advice method. The second attribute is the returning, whose value is the name of the method parameter to which the return value must be passed. The third attribute is the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="simpleServiceBean"
		class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>

	<bean id="doBeforeAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />

	<bean id="doAfterAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />

	<bean id="doAfterReturningAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />

	<aop:config>
		<aop:aspect id="aspects" ref="doBeforeAspect">
			<aop:pointcut id="pointCutBefore"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:before method="doBefore" pointcut-ref="pointCutBefore" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAfterAspect">
			<aop:pointcut id="pointCutAfter"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after method="doAfter" pointcut-ref="pointCutAfter" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAfterReturningAspect">
			<aop:pointcut id="pointCutAfterReturning"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after-returning method="doAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" />
		</aop:aspect>

	</aop:config>

</beans>

5.4 <aop:after-throwing>

The <aop:after-throwing> element is used inside the <aop:aspect> element to declare an AfterThrowing aspect. It also has three attributes. The first attribute is the method, whose value is the name of the advice method. The second attribute is the throwing, whose value is the name of the method parameter to which the thrown exception must be passed. The third attribute is the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="simpleServiceBean"
		class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>

	<bean id="doBeforeAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />

	<bean id="doAfterAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />

	<bean id="doAfterReturningAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />

	<bean id="doAfterThrowingAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />

	<aop:config>

		<aop:aspect id="aspects" ref="doBeforeAspect">
			<aop:pointcut id="pointCutBefore"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:before method="doBefore" pointcut-ref="pointCutBefore" />
		</aop:aspect>
		
		<aop:aspect id="aspects" ref="doAfterAspect">
			<aop:pointcut id="pointCutAfter"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after method="doAfter" pointcut-ref="pointCutAfter" />
		</aop:aspect>
		
		<aop:aspect id="aspects" ref="doAfterReturningAspect">
			<aop:pointcut id="pointCutAfterReturning"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after-returning method="doAfterReturning" returning="result" pointcut-ref="pointCutAfterReturning" />
		</aop:aspect>
		
		<aop:aspect id="aspects" ref="doAfterThrowingAspect" >
    <aop:pointcut id="pointCutAfterThrowing"
      expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.checkName(..))" />
    <aop:after-throwing method="doAfterThrowing" throwing="error" 
      pointcut-ref="pointCutAfterThrowing"  />
  </aop:aspect>

	</aop:config>

</beans>

5.5 <aop:around>

The <aop:around> element is used inside the <aop:aspect> element to declare an Around aspect. It has two attributes, the method whose value is the name of the advice method, and the pointcut-ref, whose value is the name of the pointcut associated to the advice, as shown below:

applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">

	<bean id="simpleServiceBean"
		class="com.javacodegeeks.snippets.enterprise.impl.SimpleServiceImpl">
		<property name="name" value="Hello" />
		<property name="id" value="12345" />
	</bean>

	<bean id="doBeforeAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoBeforeAspect" />

	<bean id="doAfterAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterAspect" />

	<bean id="doAfterReturningAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterReturningAspect" />

	<bean id="doAfterThrowingAspect"
		class="com.javacodegeeks.snippets.enterprise.aspect.DoAfterThrowingAspect" />

	<bean id="doAroundAspect" class="com.javacodegeeks.snippets.enterprise.aspect.DoAroundAspect" />

	<aop:config>

		<aop:aspect id="aspects" ref="doBeforeAspect">
			<aop:pointcut id="pointCutBefore"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:before method="doBefore" pointcut-ref="pointCutBefore" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAfterAspect">
			<aop:pointcut id="pointCutAfter"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after method="doAfter" pointcut-ref="pointCutAfter" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAfterReturningAspect">
			<aop:pointcut id="pointCutAfterReturning"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:after-returning method="doAfterReturning"
				returning="result" pointcut-ref="pointCutAfterReturning" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAfterThrowingAspect">
			<aop:pointcut id="pointCutAfterThrowing"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.checkName(..))" />
			<aop:after-throwing method="doAfterThrowing"
				throwing="error" pointcut-ref="pointCutAfterThrowing" />
		</aop:aspect>

		<aop:aspect id="aspects" ref="doAroundAspect">
			<aop:pointcut id="pointCutAround"
				expression="execution(* com.javacodegeeks.snippets.enterprise.SimpleService.sayHello(..))" />
			<aop:around method="doAround" pointcut-ref="pointCutAround" />
		</aop:aspect>


	</aop:config>

</beans>

Now. let's run the application again. The result is the same as the one in the annotations-based case.

Output

SimpleService : Method printNameId() : My name is Hello and my id is 12345
---------------
***AspectJ*** DoAfterThrowing() is running!! intercepted : checkName
Exception : java.lang.IllegalArgumentException
******
SimpleService checkName() : Exception thrown..
---------------
***AspectJ*** DoBefore() is running!! intercepted : sayHello
***AspectJ*** DoAround() is running!! intercepted : sayHello 
arguments : [Javacodegeeks]
***AspectJ*** DoAround() before is running!
SimpleService : Method sayHello() : Hello! Javacodegeeks
***AspectJ*** DoAround() after is running!
***AspectJ*** DoAfterReturning() is running!! intercepted : sayHello
Method returned value is : null
***AspectJ*** DoAfter() is running!! intercepted : sayHello
---------------

 
This was an example of AOP AspectJ in Spring.
Download the Eclipse project of this tutorial : SpringAOPAspectJexample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close