Thursday, 18 July 2013

Spring AOP Annotation Based Example


Spring AOP Example

Aspect Oriented Programming
Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points  of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic
Important Terms
Aspect- A module which has a set of APIs providing cross-cutting requirements.
Join point- This represents a point in your application where you can plug-in AOP aspect
Advice- This is the actual action to be taken either before or after the method execution.
Point cut - This is a set of one or more join points where an advice should be executed


1. Create a class to define aspect module

package com.vinod.test.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
public class MyObserver {

     * This method will execute before executing any method in side
     * com.vinod.test.aop package

    @Before("execution(* com.vinod.test.aop.*.*(..))")
    public void beforeAdvice(JoinPoint jp) {
        System.out.println("Creating  object" + jp.getTarget().getClass().getName());

     * This method will execute after executing any method

    @After("execution(* com.vinod.test.aop.*.*(..))")
    public void afterAdvice(JoinPoint jp) {
        System.out.println("Created  object" + jp.getTarget().getClass().getName());


2. Create an employee entity

package com.vinod.test.aop;

import org.springframework.stereotype.Component;

public class Employee {

    public String getName() {
        return "Raju";

    public String getAddress() {
        return "Banaglore";

3. Create Spring configuration

package com.vinod.test.aop;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
public class MySpringAOPConifg {

4. Create a Test class 

package com.vinod.test.aop;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyAOPMain {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        Employee emp = context.getBean(Employee.class);



5. Output

Creating  objectcom.vinod.test.aop.Employee

Created  objectcom.vinod.test.aop.Employee




Download example