Getting started AOP with Spring Framework

February 19, 2018

We are going to do small program using Spring Framework to study the basics of the Aspect-Oriented Programming

In this example I will create simple Java Console application
You will need aspectjrt.jar, aspectjweaver.jar and spring-aop.jar file for this application in addition to basic Spring jar file.

First you can create the Car bean class

package com.kayak;
import org.springframework.stereotype.Component;

@Component
public class Car  {
   
    private String name;

    public void setName(String name) {
        this.name = name;
    }
   
    public String getName() {
        return "Audi ";
    }
}

I have used @Component annotation to make this class as Spring Bean

Next I will create Log class with show method and this show method will be called before the getName() is called


package com.kayak;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

@Component
@Aspect
@EnableAspectJAutoProxy
public class Log {
    
    @Before("execution(* com.kayak.Car.getName(..))")
    public void show(){
        System.out.println("Log Method Show");
    }
    
}

You have @Aspect and @EnableAspectJAutoProxy annotation which we need for Aspect Orined Programming.
@Before("execution(* com.kayak.Car.getName(..))") code tells to spring ececute the show method before calling the getName() of the Car class

So to run above code you can use the following main method

package com.kayak;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class Test {
    public static void main(String[] args) {
         //ApplicationContext ctx = new  ClassPathXmlApplicationContext("bean.xml");
         ApplicationContext ctx = new  AnnotationConfigApplicationContext(Test.class);
         Car car=ctx.getBean(Car.class);
         System.out.println(car.getName());
    }
    
}

So you will get the following output

run:
Feb 19, 2018 5:39:34 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@21b8d17c: startup date [Mon Feb 19 17:39:34 IST 2018]; root of context hierarchy
Log Method Show
Audi 
BUILD SUCCESSFUL (total time: 3 seconds)