First Time Spring AOP (Annotation)

We can configure Spring AOP using XML, “as in First Time Spring AOP“, or Annotation.


  • How to implement Spring AOP using annotation?
  • Why to use annotation?


  • 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;

import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

public class Logger {

	@After("execution(* com.hmkcode.beans.User.login(..))")
	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" />


Place java files and xml file as shown below

( 4 ) Test the Application

You should get something similar to the result below (of course, not the same date and time) :)

( 5 ) Why to use annotation?

Less code!

in XML we have to define AOP in XML file as following

			<aop:aspect id="aspectUserLogger" ref="logger" >

     			<aop:pointcut id="pointCutAfter"
				expression="execution(* com.hmkcode.beans.User.login(..))" />
     			<aop:after method="log" pointcut-ref="pointCutAfter" />

While using annotation we just add few annotations @Aspect for the class and @After for the method.

Download Source Code: