Tuesday, July 6, 2010

Aspect Oriented Programming with Spring AspectJ Part5

01
package com.javacodegeeks.aspectjspring.aspects;
02

03
import org.aspectj.lang.ProceedingJoinPoint;
04
import org.aspectj.lang.annotation.Around;
05
import org.aspectj.lang.annotation.Aspect;
06

07
@Aspect
08
public class GreetingAspect {
09

10
private String message;
11

12
public void setMessage(String message) {
13
this.message = message;
14
}
15

16
@Around("execution(* com.javacodegeeks.aspectjspring.services.GreetingService.*(..))")
17
public Object advice(ProceedingJoinPoint pjp) throws Throwable {
18
String serviceGreeting = (String) pjp.proceed();
19
return message + " and " + serviceGreeting;
20
}
21

22
}
Finally locate the main Web page of your project, “index.jsp”, under /src/main/webapp folder and alter it as follows :
01
<%@ page language="java" import="org.springframework.web.context.WebApplicationContext, org.springframework.web.context.support.WebApplicationContextUtils, com.javacodegeeks.aspectjspring.services.GreetingService"%>
02
<%@page contentType="text/html" pageEncoding="UTF-8"%>
03
04
"http://www.w3.org/TR/html4/loose.dtd">
05

06
<%
07
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
08
GreetingService greetingService = (GreetingService) webApplicationContext.getBean("greetingService");
09
%>
10

11

12

13
JSP Page
14

15

16

Test service invoked and greets you by saying : <%=greetingService.sayHello()%>


17

18

Things to notice here :
Upon page load, we retrieve the Spring Web application context, and lookup our “greeting” service. All we have to do is to invoke the “sayHello()” method to see the combined greeting message from our aspect and the service

To build the application right click on your project → Run As → Maven package

To deploy the web application just copy the „.war“ file from the „target“ directory to Apache – Tomcat “webapps” folder

To lunch the application point your browser to the following address

http://localhost:8080/{application_name}/

If all went well you should see your main web page displaying the following :

“Test service invoked and greets you by saying : Hello from Greeting Aspect and Hello from Greeting Service”


You can download the project from here

No comments:

Post a Comment