Thursday, March 13, 2008

Spring AOP Simplified

Spring AOP (Aspect Oriented Programming) Simplified:

Here is my exploration os spring aop. An interceptor which logs the method name
and the time taken for each method being invoked in the path of executing a request.

Back to Basics:

What is AOP:
AOP is a philosophy that is related to style of programming.
It addresses issues that can be solved in other approaches, but in a more elegant way.
To understand the spirit of AOP, you must understand the following issues

1) Things like logging, When you enter and exit methods and time take to execute are common across
the application (Caution: logging to debug ur app is different). It need not necessarily interfere with ur code.

2) Transaction management

3) Entitlements etc

Here is an example of how to implement AOP in spring

Lets try to see when user performs any action, see if session is active and throw
and error if its not.


public class SessionInterceptor implements MethodInterceptor {

public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("Suneetha in Sarc session Interceptor");
logger.info("calling... >>" + methodInvocation.getThis() + ">> "+ methodInvocation.getMethod().getName());
System.out.println("calling... >>" + methodInvocation.getThis() + ">> "+ methodInvocation.getMethod().getName());
HttpSession session = request.getSession(false);
if (session != null) {

System.out.println("Session is healthy");

}else{
System.out.println("Session expired");
throw new SessionTimeoutException("session expired");

}

//Make sure you always have these lines of code

try {
Object retVal = methodInvocation.proceed();
return retVal;
} catch (Exception e) {
logger.error(Constants.EVENT_TYPE_DIAGNOSIS + " "
+ Constants.BUSINESS_PROCESS_NAME + " "
+ this.getClass().getName() + " ", e);
throw e;
}
}
}


So now the wiring:

In your application context.xml you shud define the above bean and
also wire the aspect to it.

As always define the bean:

bean id="sessionInterceptor" class="com.jpmchase.srgtarc.interceptor.SessionInterceptor"
property name="sarcUserService"
ref bean="sarcUserService"/
/property
/bean


Now define the Aspect bean

bean name="logAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"
property name="beanNames"
value /actions/smarc*,/actions/sMArc*,/actions/saMArc* /value
/property
property name="interceptorNames"
list
value sessionInterceptor /value
/list
/property
/bean

So the above aspect will be executed for all kinds of actions starting with

smarc or sMArc or saMArc etc



Other Killer AOP examples:


AOP thoroughly explained

spring wiki doc. Simple but profound

yes Knowledge is Power

No comments: