Professional Documents
Culture Documents
This first section of this article looks into the various terminologies that are
commonly used in the AOP Environment.
Then it moves into the support that is available in the Spring API for embedding
Aspects into an Application .
06/04/10 Spring AOP - Rajkumar J 2
Finally the article concludes by giving a Sample Application.
Introduction to AOP
The Real Problem
Since AOP is relatively new, this section devotes time in
explaining the need for Aspect Oriented Programming and the
various terminologies that are used within.
}
public long withdraw(long withdrawalAmount){
if (withdrawalAmount <= currentAmount){
return currentAmount;
}
}
06/04/10 Spring AOP - Rajkumar J 4
The above code models a simple Account Object that provides
services for deposit and withdrawal operation in the form of
Account.deposit() and Account.withdraw() methods.
Suppose say we want to add some bit of the security to the
Account class, telling that only users with BankAdmin privilege
is allowed to do the operations.
With this new requirement being added, let us see the modified
class structure below.
}
Assume that getContext().getUser() someway gives the
current User object who is invoking the operation.
The very first thing is that as soon as new requirements are coming it is
forcing the methods and the logic to change a lot which is against the
Software Design.
Remember every piece of newly added code has to undergo the Software
Development Lifecycle of Development, Testing, Bug Fixing,
Development, Testing, ....
But when you look into the implementation of these services, you
can find that apart from the normal business logic, it is doing so
many other stuffs like Logging, User Checking and Transaction
Management.
See
06/04/10 the pseudo-code below
Springthat explains
AOP - Rajkumar J this. 10
public void deposit(){
// Transaction Management
// Logging
// Checking for the Privileged User
// Actual Deposit Logic comes here
}
public void withdraw(){
// Transaction Management
// Logging
// Checking for the Privileged User
// Actual Withdraw Logic comes here
06/04/10 Spring AOP - Rajkumar J 11
}
From the above pseudo-code, it is clear that Logging, Transaction Management
and User Checking which are never part of the Deposit or the Service functionality
are made to embed in the implementation for completeness.
Specifically, AOP calls this kind of logic that cross-cuts or overlaps the existing
business logic as Concerns or Cross-Cutting Concerns.
The main idea of AOP is to isolate the cross-cutting concerns from the application
code thereby modularizing them as a different entity.
It doesn't mean that because the cross-cutting code has been externalized from the
actual implementation, the implementation now doesn't get the required add-on
functionalities.
There are ways to specify some kind of relation between the original business code
and the Concerns through some
06/04/10 techniques
Spring AOP - Rajkumarwhich
J we will see in the subsequent
12
sections.
AOP Terminologies
It is hard to get used with the AOP terminologies at first but a
thorough reading of the following section along with the illustrated
samples will make it easy.
Let us look into the majorly used AOP jargons.
Aspects
An Aspect is a functionality or a feature that cross-cuts over
objects.
The addition of the functionality makes the code to Unit Test
difficult because of its dependencies and the availability of the
various components it is referring.
For example, in the below example, Logging and Transaction
06/04/10 Spring AOP - Rajkumar J 13
Management are the aspects.
public void businessOperation(BusinessData data){
// Logging
logger.info("Business Method Called");
// Transaction Management Begin transaction.begin();
// Do the original business operation here transaction.end();
}
}catch(Exception exception){
// Exception -> Aspect code here when some exception is raised.
}
finally{ // Finally -> Even possible to have aspect code at this point too. }
06/04/10 Spring AOP - Rajkumar J 15
// Method End -> Aspect code here in the end of a method. }
In the above code, we can see that it is possible to determine
the various points in the execution of the program like Start of
the Method, End of the Method, the Exception Block, the
Finally Block where a particular piece of Aspect can be made
to execute.
A Pointcut or a Pointcut Definition will exactly tell on which Join Points the
Aspects will be applied.
To make the understanding of this term clearer, consider the following piece of
code,
aspect LoggingAspect {}
aspect TransactionManagementAspect {}
Assume that the above two declarations declare something of type Aspect. Now
consider the following piece ofSpring
06/04/10 code,AOP - Rajkumar J 17
public void someMethod(){
//Method Start
try{
// Some Business Logic Code.
}catch(Exception exception){
// Exception handler Code
}
finally{
// Finally Handler Code for cleaning resources.
}
06/04/10
// Method End Spring AOP - Rajkumar J 18
}
In the above sample code, the possible execution points, i.e. Join Points, are the
start of the method, end of the method, exception block and the finally block.
These are the possible points wherein any of the aspects, Logging Aspect or
Transaction Management Aspect can be applied.
Now consider the following Point Cut definition,
pointcut method_start_end_pointcut(){
// This point cut applies the aspects, logging and transaction, before the
// beginning and the end of the method.
}
pointcut catch_and_finally_pointcut(){
// This point cut applies the aspects, logging and transaction, in the catch
// block (whenever an exception raises) and the finally block.
}
As clearly defined, it is possible
06/04/10
to define a Point Cut that binds the Aspect
Spring AOP - Rajkumar J 19
to
a particular Join Point or some Set of Join Points.
Advice
Now that we are clear with the terms like Aspects, Point Cuts and
Join Points, let us look into what actually Advice is.
Consider
06/04/10 the following piece of -Code,
Spring AOP Rajkumar J 22
Authentication.java
public class Authentication extends BeforeAdvice{
public void before(Method method, Object[] args, Object target) throws
Throwable{
if (args[0] instanceof User){
}
}
}
The above class extends BeforeAdvice, thereby telling that before() method will be
called before the execution of the method call.
CleanUpOperation.java
Note that, afterReturning() will be method that will be called once the method returns normal
execution.
06/04/10 Spring AOP - Rajkumar J 25
If some exception happens in the method execution the afterReturning() method will never be
called.
Throws Advice
When some kind of exception happens during the execution of a method, then to handle the
exception properly, Throws Advice can be used through the means of
org.springframework.aop.ThrowsAdvice.
Note that this interface is a marker interface meaning that it doesn't have any method
within it.
The method signature inside the Throws Advice can take any of the following form,
For example, in a File Copy program, if some kind of exception happens in the mid-way
then the newly created target file has to be deleted as the partial content in the file doesn't
carry any sensible meaning.
06/04/10 Spring AOP - Rajkumar J 26
It can be easily achieved through the means of Throws Advice.
DeleteFile.java
public class DeleteFile implements ThrowsAdvice{
public void afterThrowing(Method method, Object[] args, Object target,
IOException exception){
String targetFileName = (String)args[2]; // Code to delete the target file.
}
}
Note that the above method will be called when an Exception, that
too of type IOException is thrown by the File Copy Program.
The Configuration File should be populated with the following information for
gaining this kind of support.
<bean id="regExpAdvisor"
class="org.springframework.aop.support.RegExpPointcutAdvisor">
<property name="pattern">
<value>m*1<value>
</property>
</bean>
The logic is as simple as it returns the summation of the two numbers given
as arguments.
Note that, in the later section we will see how Advices get bound with this
Implementation Class.
AdderImpl.java
package net.javabeat.spring.aop.introduction.test;
public class AdderImpl implements Adder {
public int add(int a, int b){ return a+b; }
}
06/04/10 Spring AOP - Rajkumar J 39
Before Advice Implementation
LogBeforeCallAdvice.java
package net.javabeat.spring.aop.introduction.test;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class LogBeforeCallAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object target) {
System.out.println("Before Calling the Method"); }
}
LogAfterReturningAdvice.java
package net.javabeat.spring.aop.introduction.test;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class LogAfterReturningAdvice implements AfterReturningAdvice{
public void afterReturning(Object returnValue, Method method, Object[] args,
Object target) throws Throwable {
System.out.println("After Normal Return from Method");
}
}
06/04/10 Spring AOP - Rajkumar J 41
Throws Advice Implementation
This Advice will be called when some kind of Exception is caught during the
method invocation. We have added a simple logic to simlate the exception
when the user inputs are 0 and 0.
LogAfterThrowsAdvice.java
package net.javabeat.spring.aop.introduction.test;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class LogAfterThrowsAdvice implements ThrowsAdvice{
public void afterThrowing(Method method, Object[] args, Object target,
Exception exception){
System.out.println("Exception is thrown on method " + method.getName());
}
}
06/04/10 Spring AOP - Rajkumar J 42
Around Advice Implementation
This Advice takes the entire control during the Method Execution.
It decides whether the add() method should be called or not based on the user
inputs.
Note that, only if the user inputs are not 0 and 0, then the add() method will
be called through MethodInvocation.proceed().
LogAroundAdvice.java
package net.javabeat.spring.aop.introduction.test;
import org.aopalliance.intercept.*;
public class LogAroundAdvice implements MethodInterceptor{
public Object invoke(MethodInvocation methodInvocation) throws
Throwable {
Object arguments[] = methodInvocation.getArguments();
int number1 = ((Integer)arguments[0]).intValue();
int number2 = ((Integer)arguments[1]).intValue();
if (number1 == 0 && number2 == 0){
throw new Exception("Dont know
06/04/10 Spring AOP - how toJ add 0 and 0!!!"); }
Rajkumar 43
return methodInvocation.proceed(); } }
Configuration File
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
"net.javabeat.spring.aop.introduction.test.LogAroundAdvice" />
<!-- Implementation Class --> <bean id = "adderImpl" class =
"net.javabeat.spring.aop.introduction.test.AdderImpl" />
</beans>
Test Class
Following is the test class for the Adder Service.
The code loads the Bean Definition File by depending on the BeanFactory class.
Watch carefully in the output for the various Advices getting called.
Also, we have made to activate the Simulated Exception by passing 0 and 0 as arguments
to the add() method call thereby making use of the Throws Advice.
AdderTest.java
package net.javabeat.spring.aop.introduction.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*; public class AdderTest {
public static void main(String args[]){
Resource resource = new FileSystemResource("./src/aop-test.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Adder adder = (Adder)factory.getBean("adder");
int result = adder.add(10,10);
System.out.println("Result = " + result);
result = adder.add(0,0);
06/04/10 Spring AOP - Rajkumar J 47
System.out.println("Result = " + result); }}
Conclusion
This chapter provided information on how to use Spring AOP for programming the Aspects
in an Application.
It started with defining what Aspects are and what are problems in having the Aspects
directly embedded into the Application and how to separate them using AOP.
It then looked briefly into the various AOP Terminologies like Advice, Point Cut, Join
Points etc.
Then it moved on into the various support for creating Advices using Spring AOP.
Also covered in brief are the Static Point Cuts like Name Method Match and Regular
Expression Point Cuts.
Finally the article concluded with a Sample Application that illustrates the usage of different
06/04/10 Spring AOP - Rajkumar J 48
Advices.