Tuesday, July 6, 2010

Aspect Oriented Programming with Spring AspectJ Part3

The next step is to provide hooks for the web application so as to load the Spring context upon startup.

Locate the „web.xml“ file under /src/main/webapp/WEB-INF and add the following :

For loading the Spring context upon startup,
1<listener>
2 <listener-class>
3 org.springframework.web.context.ContextLoaderListener
4 listener-class>
5listener>

Now lets create the applicationContext.xml file that will drive Spring container. Create the file under /src/main/webapp/WEB-INF directory. An example „applicationContext.xml“ is presented below
Things to notice here :
  1. Change the base-package attribute of the context:component-scan element to whatever is the base package of your project so as to be scanned for Spring components
  2. We have to define our aspects in “applicationContext.xml” only if we want to inject dependences to them
  3. AspectJ denotes the term of “aspect association”. It defines how to manage aspect state. The following state associations are supported:
    • Per JVM – one shared aspect instance is constructed and used (default)
    • Per object – aspect has its own state per every advised object
    • Per control flow – aspect has its own state per particular control flow
      All AspectJ aspect classes have “hasAspect()” and “aspectOf()” static methods. These methods are implicitly generated by AspectJ compiler/load time weaver. So, for the default aspect state there is a single aspect instance that can be retrieved using the “aspectOf()” method
Lets create now the “greeting” Spring service and the relevant “greeting” AspectJ aspect. Create a sub – package named “services” under your main package and place the “GreetingService” class there. An example “greeting” service is shown below :
01package com.javacodegeeks.aspectjspring.services;
02
03import org.springframework.stereotype.Service;
04
05@Service("greetingService")
06public class GreetingService {
07
08 public String sayHello() {
09 return "Hello from Greeting Service";
10 }
11
12}
Create a sub – package named “aspects” under your main package and place the “GreetingAspect” class there. An example “greeting” aspect is shown below :

No comments:

Post a Comment