Project Setup
Let's create a simple Spring project to demonstrate AOP concepts.
Step-1: Create a maven project using Eclipse or Spring Tool Suite.
Group Id= org.apache.maven.archetypes
Artifact Id= maven-archetype-quickstart
version= 1.1
Step-2: Add required dependencies in pom.xml.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
Step-3: Create a Spring Configuration file i.e. config.xml in the main class. This will be used to configure the Spring component and AOP aspects.
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- bean definitions here -->
<bean name="purchase" class="com.aop.aopexample.serviceimpl.PurchaseServiceImpl"/>
<bean name="aspect" class="com.aop.aopexample.aspect.Aspect"/>
</beans>
Step-4: Create a Service Class.
package com.aop.aopexample.service;
public class PurchaseService {
public void buyNow() {
// your code
System.out.println("Added to Cart!!");
// your code
System.out.println("Order Placed!!");
}
}
Step-5: Create an Aspect Class.
package com.aop.aopexample.aspect;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
@org.aspectj.lang.annotation.Aspect
public class Aspect {
@Before(value = "execution(* com.aop.aopexample.serviceimpl.PurchaseServiceImpl.buyNow())")
public void printBefore() {
System.out.println("Please Signin");
}
@After(value = "execution(* com.aop.aopexample.serviceimpl.PurchaseServiceImpl.buyNow())")
public void printAfter() {
System.out.println("Please Signout");
}
}
Step-6: The Main Application Class
package com.aop.aopexample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.aop.aopexample.service.PurchaseService;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/aop/aopexample/config.xml");
PurchaseService purchaseObject = context.getBean("purchase", PurchaseService.class);
purchaseObject.buyNow();
}
}
Step-7: Now Run the main class i.e. App.java
Here the Before Advice Execute first then the buyNow() method after that After Advice will be executed.
Output:
Please Signin
Added to Cart!!
Order Placed!!
Please Signout