AOP is…let us see!
Objectives
- How to implement AOP using Spring?
- What is AOP?
Environment
- Eclipse (Indigo or any)
Library
- Spring framework 3.x (jars) some of them! 3.x http://www.springsource.org/spring-framework
- Other jars you can find them on http://mvnrepository.com/ or http://www.jarfinder.com
- aopalliance-1.0.jar
- aspectjtools-1.6.0.jar
- cglib-nodep-2.2.3.jar
- commons-logging-1.1.1.jar
The Story:
Every time a user login we would like to keep a record of his login action.
( 1 ) Create Java Project & Add jars to lib Folder
- Create a new java project “SpringAOP”
- Create folder “lib”
- Copy jar files to “lib”
- Add jars to the java building path
( 2 ) Java Code (User.java + Logger.java + Main.java)
User.java plain java bean
package com.hmkcode.beans;
public class User {
//constructor
public User(){}
//method login
public void login(){
System.out.println("User is trying to login");
}
}
Logger.java logs user login activity
package com.hmkcode.beans;
import java.util.Calendar;
public class Logger {
public void log(){
System.out.println("user has logged in @"+Calendar.getInstance().getTime());
}
}
Main.java runs the application
package com.hmkcode;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hmkcode.beans.User;
public class Main {
public static void main(String args[]){
// Laod spring-config.xml file
ApplicationContext ctx = new ClassPathXmlApplicationContext("com/hmkcode/config/spring-config.xml");
((User) ctx.getBean("user")).login();
}
}
( 3 ) XML Configuration File (spring-config.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<aop:aspectj-autoproxy />
<bean id="user" class="com.hmkcode.beans.User" />
<bean id="logger" class="com.hmkcode.beans.Logger" />
<aop:config>
<aop:aspect id="aspectUserLogger" ref="logger" >
<!-- @After -->
<aop:pointcut id="pointCutAfter"
expression="execution(* com.hmkcode.beans.User.login(..))" />
<aop:after method="log" pointcut-ref="pointCutAfter" />
</aop:aspect>
</aop:config>
</beans>
Place java files and xml file as shown bleow
( 4 ) Test the Application
You should get something similar to the result below (of course, not the same date and time)
( 5 ) What is AOP?
Simply, (after/before) a method “A” is called call another method “B” ! without writing “code” calling B.
AOP = Aspect Oriented Programming
Download Source Code: SpringAOP.zip


