Spring AOP

Hello Readers,

Recently a friend asked me if I can tell him basics of Spring AOP (Aspect Oriented Programming). Yeah, so I have been thinking for a few days to write a post discussing basic example of Spring AOP so that it can be referred any time.

The documentation for Spring AOP is here.

Spring AOP solves the problem of applying a common functionality across multiple classes in the application. For eg: functionalities like security, transaction management, logging are generally applied to multiple classes. With AOP, you can define such functionality at 1 place and using regular expression specify the classes to attach the functionality.

AOP concepts:

1) Aspect: It is the common functionality. Like security, transaction management, logging, etc. An aspect is basically a class with methods.

2) Pointcut: It consists of a regular expression. Any method in any class that matches this regex can have the aspect attached to it.

3) Advice:  It specifies when (before?, after?) the aspect should be applied if there is a regex match.

Scenario: Assume you have a Util class and you want to log each invocation of its methods. Yeah yeah this Util class is very confidential ;).

Pointcut: SpringAOPUtils.java

package com.springaop.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SpringAOPUtils {
 public String getCorrectViewName(HttpServletRequest req,
 HttpServletResponse res) {

String viewName = null;

// check for req method, if post send to welcome.jsp, else send to
 // login.jsp
 if (req.getMethod().indexOf("POST") != -1
 && req.getParameter("userid").indexOf("admin") != -1
 && req.getParameter("password").indexOf("admin") != -1) {
 viewName = "welcome";
 } else {
 viewName = "login";
 }

System.out.println("req method: " + req.getMethod() + ", viewName: "
 + viewName);

return viewName;

}

}

Aspect: SampleAspects.java

package com.springaop.aspects;

public class SampleAspects {

public void runBefore () {
 System.out.println("Watch it! Something great is about to run...");
 }

 public void runAfter () {
 System.out.println("Whoa! How was that?");
 }

}

We need to attach the above pointcut and aspect together. We also want to define advice i.e. when the aspect should run. All this can be configured in XML.

...
<bean id="loginController" class="com.springaop.web.LoginController">
 <property name="springAOPUtils" ref="springAOPUtils" />
 <!--<span class="hiddenSpellError" pre=""-->bean>

<bean id="sampleAspects" class="com.springaop.aspects.SampleAspects" />

<bean id="springAOPUtils" class="com.springaop.util.SpringAOPUtils" />

<aop:config>
 <aop:aspect ref="sampleAspects">
  <aop:pointcut expression="execution(* com.springaop.util.SpringAOPUtils.*(..))" id="pointcut1"/>
  <aop:before method="runBefore" pointcut-ref="pointcut1"/>
  <aop:after method="runAfter" pointcut-ref="pointcut1"/>
 </aop:aspect>
</aop:config>
...

<aop:config>: Wraps all aop related tags.

<aop:aspect>: Contains reference of the aspect.

<aop:pointcut>: Defines the expression of when (advice) the aspect should run. Above pointcut expression is true for all methods inside com.springaop.util.SpringAOPUtils class.

<aop:before>: Defines before advice. Above says execute runBefore method before the method specified in pointcut is executed.

<aop:after>: Defines after advice. So above says execute runAfter method after the method specified in pointcut is executed.

Below is LoginController.java that calls getCorrectViewName method of SpringAOPUtils.

package com.springaop.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.springaop.util.SpringAOPUtils;

public class LoginController extends AbstractController {

private SpringAOPUtils springAOPUtils;

public SpringAOPUtils getSpringAOPUtils() {
 return springAOPUtils;
 }

public void setSpringAOPUtils(SpringAOPUtils springAOPUtils) {
 this.springAOPUtils = springAOPUtils;
 }

protected ModelAndView handleRequestInternal(HttpServletRequest req,
 HttpServletResponse res) throws Exception {

System.out.println("before invoking SpringAOPUtils method");

String viewName = getSpringAOPUtils().getCorrectViewName(req, res);

System.out.println("after invoking SpringAOPUtils method");

return new ModelAndView(viewName);
 }

}

When getCorrectViewName is called first time, it’s a get request. Below gets printed on Tomcat console:

before invoking SpringAOPUtils method
Watch it! Something great is about to run...
req method: GET, viewName: login
Whoa! How was that?
after invoking SpringAOPUtils method

In login.jsp, I am requested for userid and password. After entering admin and admin (as checked in getCorrectViewName method), I am taken to welcome.jsp. Below is appended to Tomcat console:

before invoking SpringAOPUtils method
Watch it! Something great is about to run...
req method: POST, viewName: welcome
Whoa! How was that?
after invoking SpringAOPUtils method

Thus we have executed runBefore method of SampleAspects.java before executing getCorrectViewName method of SpringAOPUtils.java. Similarly, runAfter method is executed after.

The web project can be downloaded from here.

WAR file can be downloaded from here.

Hopefully above gives basic idea of AOP and a working example. Looking forward to your excellent feedback.

Your’s Truly

Advertisements

About Badal Chowdhary

I am a Software Engineer by profession. I have done SCJP and SCWCD certifications. Like working on cutting edge technologies and frameworks. Driven by challenges and fascinated by technology. I love playing and watching sports: Cricket, Ping Pong, Tennis, Badminton, Racket Ball and Gym.
This entry was posted in Spring and tagged , , , , , . Bookmark the permalink.

One Response to Spring AOP

  1. manoj says:

    Thanks 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s