Spring AOP Before Advice

Before advice:

Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

Let’s Understand using Example

Project Structure


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.Before;
import org.aspectj.lang.annotation.Aspect;
 
@Aspect
public class LoggingAspect 
{
 
	@Before("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 TestBeforeAdvise 
{
 
	public static void main(String[] args) 
	{
 
	   ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
 
	   Student st=(Student)context.getBean("stu");
 
       st.get_info();
 
       System.out.println(st.getName());
 
	}
}

Output:

Download this project developed using eclipse

BeforeAdvise

Leave a Reply

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