Creating First Spring AOP program

Project Structure


Let’s Create simple Spring AOP application to understand how Spring AOP works.
here I have used After advise which means this advise will run after method is called.

Example: when a method is execute, Spring AOP can hijack the executing method, and add extra functionality after the method execution.

Student.java


package com.training;
 
public class Student 
{
 
	String name;
 
	public String getName() 
	{
		return name;
	}
 
	public void setName(String name) 
	{
		this.name = name;
	}
 
 
	public void get_info()
	{
		System.out.println("Hello "+name);	
	}
 
}

LoggingAspect.java


package com.training;
 
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
 
@Aspect
public class LoggingAspect 
{
 
	@After("execution(public void get_info())")
	public void loggingadvise()
	{
 
		System.out.println("Advise is runnning before get_info() method is called.....");
 
	}
 
}

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"
		xmlns:context="http://www.springframework.org/schema/context"
		xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
				http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-5.0.0.xsd">
 
<aop:aspectj-autoproxy/>	
 
<bean name="stu" class="com.training.Student">
<property name="name"  value="bhavesh_lakhani" />
</bean>
 
<bean name="loggingAspect" class="com.training.LoggingAspect"/>
 
</beans>

TestAfterAdvise.java


 
package com.training;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestAfterAdvise 
{
 
	public static void main(String[] args) 
	{
 
	   ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
 
	   Student st=(Student)context.getBean("stu");
 
       st.get_info();
 
	}
}

Output:

Download project developed using eclipse
Spring-AOP-Example

Leave a Reply

Your email address will not be published. Required fields are marked *