Showing posts with label advice. Show all posts
Showing posts with label advice. Show all posts

Tuesday, April 26, 2011

Need for AOP

Aspect-Oriented Programming (AOP) complements Object-Oriented Programming (OOP) by providing another way of thinking about program structure. 

Consider a following method code (say in a webservice method):

try{
   //start new session
   //some business logic
   //commit transaction
}catch(Exception ex)
{
   //handle exception
}finally{
   //close session
}
//logging
//return the output


So like this method above, there will be lots of other methods similar to this....But don't you think it will be nice if  we only deal with business logic, rather than writing the repeatative code like handling exceptions, logging,security management, etc. These code tidbits are called concerns or aspects or advices (though described below). These are used interchangeably, though there are slight differences, which we will see in course of time.

So this is where AOP comes into picture. We can simply write our code as a simple business logic, without dealing with above mentioned concerns or repeatative code. For eg. for security checks, you can add the authorization into the execution path with a type of IOC implementation called AOP or aspect oriented programming. 

See Aop introduction

Sunday, March 20, 2011

Spring : Xml style configuration for pointcuts (Before advice)

The Aspect Class:

import org.aspectj.lang.JoinPoint;

//This is an Aspect class
public class LoggingAspect {

//This is an advice.
//Pointcut means where will this advice be applied.
public void log(JoinPoint joinPoint) {
System.out.println("common logging code executed for : "+joinPoint);
}

}

The configuration file:

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

<!-- Tells the container we will be using AspectJ.
Also tells the container to use the proxy approach for executing aspects -->
<aop:aspectj-autoproxy />

<bean id="customerService" class="service.CustomerServiceImpl" />

<bean id="loggingAspect" class="com.xxxx.LoggingAspect" />

<!-- Aop config start -->

<aop:config>
<aop:pointcut expression="execution(public * apply*(..))" id="pointcut1" />
<aop:aspect ref="loggingAspect">
<aop:before method="log" pointcut-ref="pointcut1" />
</aop:aspect>
</aop:config>

</beans>


Note that we are using "aop" namespace in the xml to configure it to aspect class.

 


 

Chitika