Monday, February 8, 2010

Spring AOP Example - Person Service

Project: Spring_AOP
Description: Have AOP attached to Person Service
IDE: Eclipse
JARs:

aspectj-1.6.8.jar
aspectjweaver.jar
commons-logging-1.1.1.jar
spring.jar (2.5.6)

XML Configuration


<!-- this is the object that will be proxied by Spring's AOP infrastructure --><bean id="personService" class="com.somellc.aop.DefaultPersonService"/> <!-- this is the actual advice itself --><bean id="profiler" class="com.somellc.aop.SimpleProfiler"/><aop:config><aop:aspect ref="profiler"> <aop:pointcut id="aopafterMethod" expression="execution(* com.somellc.aop.DefaultPersonService.getAfter())"/> <aop:after pointcut-ref="aopafterMethod" method="afterMethod"/> <aop:pointcut id="aopBefore" expression="execution(* com.somellc.aop.DefaultPersonService.getBefore(String)) and args(myName)"/> <aop:before pointcut-ref="aopBefore" method="beforeMethod"/>
</aop:aspect></aop:config>


Client.java
public class AOPClient {
public static void main(final String[] args) throws Exception {
String filename = "aop-context.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(filename);
IPersonService ipersonService = (IPersonService)context.getBean("personService");
ipersonService.getPerson("John Doe", 12);
ipersonService.getAfter();
ipersonService.getBefore("Jack Smith");
}
}



PersonService Interface:
public class AOPClient {
public static void main(final String[] args) throws Exception {
String filename = "aop-context.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(filename);
IPersonService ipersonService = (IPersonService)context.getBean("personService");
ipersonService.getPerson("John Doe", 12);
ipersonService.getAfter();
ipersonService.getBefore("Jack Smith");
}
}



Person.java
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Person(String nm, int ag) {
name = nm;
age = ag;
}
}



Person Service Class:
public class DefaultPersonService implements IPersonService {
public Person getPerson(String name, int age) {
return new Person(name, age);
}
public void getAfter() {;}
public void getBefore(String myName) {;}
}



Profiler Java class:
public class SimpleProfiler {
public void afterMethod() throws Throwable {
System.out.println("After the method is called");
}
public void beforeMethod(String myName){
System.out.println("beforeMethod is called. My name is "+myName);
}
}

No comments:

Post a Comment