First Time Spring AOP

AOP is…let us see!


  • How to implement AOP using Spring?
  • What is AOP?


  • Eclipse (Indigo or any)


  •      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 ( + + plain java bean

package com.hmkcode.beans;

public class User {

	public User(){}

	//method login
	public void login(){
		System.out.println("User is trying to login");
} 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());
} runs the application

package com.hmkcode;

import org.springframework.context.ApplicationContext;

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=""

		<aop:aspectj-autoproxy />
		<bean id="user" class="com.hmkcode.beans.User" />
		<bean id="logger" class="com.hmkcode.beans.Logger" />

			<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" />

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: